From 0485fd3bee4149c2b16efb410bb3cafa5424ff33 Mon Sep 17 00:00:00 2001 From: Alexey Date: Sat, 3 Jan 2026 15:43:22 +0200 Subject: [PATCH] add register method --- api/auth/register.go | 45 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 api/auth/register.go diff --git a/api/auth/register.go b/api/auth/register.go new file mode 100644 index 0000000..a16e25f --- /dev/null +++ b/api/auth/register.go @@ -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) +}