add register method

This commit is contained in:
2026-01-03 15:43:22 +02:00
parent f2f7819f8c
commit 0485fd3bee

45
api/auth/register.go Normal file
View 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)
}