forked from mtusi2026/mtusi2026lab2
50 lines
1.2 KiB
Go
50 lines
1.2 KiB
Go
package http
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/charawein/mtusi2026lab2/internal/service"
|
|
"github.com/charawein/mtusi2026lab2/internal/transport/httputil"
|
|
)
|
|
|
|
type UserHandler struct {
|
|
users *service.UserService
|
|
}
|
|
|
|
func NewUserHandler(users *service.UserService) *UserHandler {
|
|
return &UserHandler{users: users}
|
|
}
|
|
|
|
func (h *UserHandler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
|
var body struct {
|
|
Username string `json:"username"`
|
|
DisplayName string `json:"display_name"`
|
|
Password string `json:"password"`
|
|
}
|
|
if err := httputil.DecodeJSON(r, &body); err != nil {
|
|
httputil.WriteError(w, r, err)
|
|
return
|
|
}
|
|
|
|
u, err := h.users.Register(r.Context(), body.Username, body.DisplayName, body.Password)
|
|
if err != nil {
|
|
httputil.WriteError(w, r, err)
|
|
return
|
|
}
|
|
httputil.WriteJSON(w, r, http.StatusCreated, u)
|
|
}
|
|
|
|
func (h *UserHandler) CurrentUser(w http.ResponseWriter, r *http.Request) {
|
|
uid := httputil.UserIDFromContext(r.Context())
|
|
if uid == "" {
|
|
httputil.WriteError(w, r, service.ErrUnauthorized)
|
|
return
|
|
}
|
|
u, err := h.users.GetByID(r.Context(), uid)
|
|
if err != nil {
|
|
httputil.WriteError(w, r, err)
|
|
return
|
|
}
|
|
httputil.WriteJSON(w, r, http.StatusOK, u)
|
|
}
|