Перенесите реализацию ЛР 4 на стенд ЛР 5

This commit is contained in:
2026-11-18 15:33:31 +03:00
parent 276dbdad8a
commit 911d97a77a
153 changed files with 17451 additions and 1 deletions
+70
View File
@@ -0,0 +1,70 @@
package user
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"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 the authentication middleware.
func (h *Handler) Register(public, protected gin.IRouter) {
public.POST("/users", h.register)
protected.GET("/users/me", httpx.WithUser(h.me))
}
type createRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
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, req.Password)
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))
}