Перенести решение лабораторной 1 как основу для лабораторной 2

This commit is contained in:
2026-10-06 11:54:05 +03:00
parent 65003b6119
commit 5c3f2bfad0
54 changed files with 4472 additions and 0 deletions
+70
View File
@@ -0,0 +1,70 @@
package user
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/auth"
"messenger/internal/platform/httpx"
)
type Handler struct {
users *Service
}
func NewHandler(users *Service) *Handler {
return &Handler{users: users}
}
// Register mounts registration on the public router and the current-user
// endpoint on the router guarded by RequireUser.
func (h *Handler) Register(public, protected gin.IRouter) {
public.POST("/users", h.register)
protected.GET("/users/me", auth.WithUser(h.me))
}
type createRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
}
type Response struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
func ToResponse(u User) Response {
return Response{
ID: u.ID.String(),
Username: u.Username,
DisplayName: u.DisplayName,
CreatedAt: httpx.Timestamp(u.CreatedAt),
}
}
func (h *Handler) register(c *gin.Context) {
var req createRequest
if err := httpx.DecodeJSON(c, &req); err != nil {
httpx.Error(c, err)
return
}
u, err := h.users.Register(c.Request.Context(), req.Username, req.DisplayName)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusCreated, ToResponse(u))
}
func (h *Handler) me(c *gin.Context, actor uuid.UUID) {
u, err := h.users.GetByID(c.Request.Context(), actor)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusOK, ToResponse(u))
}