add register method
This commit is contained in:
45
api/auth/register.go
Normal file
45
api/auth/register.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package api_auth
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type registerRequest struct {
|
||||
Username string `json:"username"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type registerResponse struct {
|
||||
UserID uint `json:"id"`
|
||||
Username string `json:"username"`
|
||||
}
|
||||
|
||||
func (h *authHandler) handleRegister(w http.ResponseWriter, r *http.Request) {
|
||||
var req registerRequest
|
||||
err := json.NewDecoder(r.Body).Decode(&req)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid request payload", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.a.Register(req.Username, req.Email, req.Password)
|
||||
if err != nil {
|
||||
slog.Error("Failed to register user", "error", err)
|
||||
http.Error(w, "Registration failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
err = json.NewEncoder(w).Encode(registerResponse{
|
||||
UserID: user.ID,
|
||||
Username: user.Username,
|
||||
})
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to encode response", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
Reference in New Issue
Block a user