feat: port backend implementation from lab1

This commit is contained in:
Голиков Maximillian Антон
2026-09-30 22:32:04 +03:00
parent 65003b6119
commit 380d0ef710
34 changed files with 1795 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
package dto
import (
"high-loud-apps-labs/internal/domain"
)
type CreateChatRequest struct {
Title string `json:"title" binding:"required,min=1,max=100"`
MemberIDs []string `json:"member_ids" binding:"required,min=1,max=100,dive,uuid"`
}
type ChatResponse struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt string `json:"created_at"`
}
type ChatPageResponse struct {
Items []ChatResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func ChatFromDomain(c *domain.Chat) ChatResponse {
return ChatResponse{
ID: c.ID,
Title: c.Title,
MemberIDs: append([]string(nil), c.MemberIDs...),
CreatedAt: c.CreatedAt.UTC().Format(timeFormat),
}
}
func ChatsFromDomain(items []domain.Chat) []ChatResponse {
out := make([]ChatResponse, len(items))
for i := range items {
out[i] = ChatFromDomain(&items[i])
}
return out
}
+69
View File
@@ -0,0 +1,69 @@
package dto
import (
"errors"
"high-loud-apps-labs/internal/domain"
)
// делаем вложенный ответ через вкладку ErrorBody в обертку.
type ErrorBody struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
type ErrorResponse struct {
Error ErrorBody `json:"error"`
}
type coded interface {
Code() domain.ErrorCode
}
func ErrorFromDomain(err error, requestID string) ErrorResponse {
var c coded
if errors.As(err, &c) {
return ErrorResponse{Error: ErrorBody{
Code: string(c.Code()),
Message: err.Error(),
RequestID: requestID,
}}
}
code := domain.CodeInternalError
switch {
case errors.Is(err, domain.ErrNotFound):
code = domain.CodeNotFound
case errors.Is(err, domain.ErrAlreadyExists):
code = domain.CodeConflict
case errors.Is(err, domain.ErrInvalidInput):
code = domain.CodeInvalidRequest
case errors.Is(err, domain.ErrForbidden):
code = domain.CodeUnauthorized
case errors.Is(err, domain.ErrUnsupportedMediaType):
code = domain.CodeUnsupportedMediaType
}
return ErrorResponse{Error: ErrorBody{
Code: string(code),
Message: err.Error(),
RequestID: requestID,
}}
}
func StatusFromError(err error) int {
switch {
case errors.Is(err, domain.ErrNotFound):
return 404
case errors.Is(err, domain.ErrAlreadyExists):
return 409
case errors.Is(err, domain.ErrInvalidInput):
return 400
case errors.Is(err, domain.ErrForbidden):
return 401
case errors.Is(err, domain.ErrUnsupportedMediaType):
return 415
default:
return 500
}
}
+5
View File
@@ -0,0 +1,5 @@
package dto
type HealthResponse struct {
Status string `json:"status"`
}
+40
View File
@@ -0,0 +1,40 @@
package dto
import (
"high-loud-apps-labs/internal/domain"
)
type CreateMessageRequest struct {
Text string `json:"text" binding:"required,min=1,max=4000"`
}
type MessageResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt string `json:"created_at"`
}
type MessagePageResponse struct {
Items []MessageResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
func MessageFromDomain(m *domain.Message) MessageResponse {
return MessageResponse{
ID: m.ID,
ChatID: m.ChatID,
SenderID: m.SenderID,
Text: m.Text,
CreatedAt: m.CreatedAt.UTC().Format(timeFormat),
}
}
func MessagesFromDomain(items []domain.Message) []MessageResponse {
out := make([]MessageResponse, len(items))
for i := range items {
out[i] = MessageFromDomain(&items[i])
}
return out
}
+28
View File
@@ -0,0 +1,28 @@
package dto
import (
"high-loud-apps-labs/internal/domain"
)
const timeFormat = "2006-01-02T15:04:05.000000Z07:00"
type CreateUserRequest struct {
Username string `json:"username" binding:"required,min=3,max=32"`
DisplayName string `json:"display_name" binding:"required,min=1,max=100"`
}
type UserResponse struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
func UserFromDomain(u *domain.User) UserResponse {
return UserResponse{
ID: u.ID,
Username: u.Username,
DisplayName: u.DisplayName,
CreatedAt: u.CreatedAt.UTC().Format(timeFormat),
}
}
+52
View File
@@ -0,0 +1,52 @@
package handler
import (
"bytes"
"encoding/json"
"errors"
"io"
"mime"
"strings"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"high-loud-apps-labs/internal/domain"
)
func bindStrictJSON(c *gin.Context, dst any) error {
ct := c.GetHeader("Content-Type")
mediaType, _, err := mime.ParseMediaType(ct)
if ct == "" || err != nil || !strings.EqualFold(mediaType, "application/json") {
return &domain.UnsupportedMediaTypeError{MediaType: ct}
}
body, err := io.ReadAll(c.Request.Body)
if err != nil {
return &badRequestError{msg: "не удалось прочитать тело запроса"}
}
_ = c.Request.Body.Close()
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
if errors.Is(err, io.EOF) {
return &badRequestError{msg: "тело запроса обязательно"}
}
return &badRequestError{msg: err.Error()}
}
// Отклоняем любой непустой остаток после первого JSON-значения.
var extra json.RawMessage
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
return &badRequestError{msg: "тело запроса содержит данные после JSON"}
}
if v := binding.Validator; v != nil {
if err := v.ValidateStruct(dst); err != nil {
return &badRequestError{msg: err.Error()}
}
}
return nil
}
+88
View File
@@ -0,0 +1,88 @@
package handler
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"high-loud-apps-labs/internal/httpapi/dto"
"high-loud-apps-labs/internal/httpapi/middleware"
"high-loud-apps-labs/internal/service"
)
type ChatHandler struct {
chats *service.ChatService
}
func NewChatHandler(chats *service.ChatService) *ChatHandler {
return &ChatHandler{chats: chats}
}
func (h *ChatHandler) Create(c *gin.Context) {
var req dto.CreateChatRequest
if err := bindStrictJSON(c, &req); err != nil {
respondError(c, err)
return
}
me := middleware.CurrentUser(c)
chat, err := h.chats.Create(c.Request.Context(), me.ID, req.Title, req.MemberIDs)
if err != nil {
respondError(c, err)
return
}
c.JSON(http.StatusCreated, dto.ChatFromDomain(chat))
}
func (h *ChatHandler) Get(c *gin.Context) {
me := middleware.CurrentUser(c)
chatID, err := parseUUIDPathParam(c, "chat_id")
if err != nil {
respondError(c, err)
return
}
chat, err := h.chats.Get(c.Request.Context(), me.ID, chatID)
if err != nil {
respondError(c, err)
return
}
c.JSON(http.StatusOK, dto.ChatFromDomain(chat))
}
func (h *ChatHandler) List(c *gin.Context) {
me := middleware.CurrentUser(c)
limit, cursor, err := parseListQuery(c)
if err != nil {
respondError(c, err)
return
}
items, next, err := h.chats.List(c.Request.Context(), me.ID, limit, cursor)
if err != nil {
respondError(c, err)
return
}
c.JSON(http.StatusOK, dto.ChatPageResponse{
Items: dto.ChatsFromDomain(items),
NextCursor: next,
})
}
func parseListQuery(c *gin.Context) (int, *string, error) {
limit := 50
if v := c.Query("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 || n > 100 {
return 0, nil, &badRequestError{msg: "limit должен быть целым 1..100"}
}
limit = n
}
var cursor *string
if v := c.Query("cursor"); v != "" {
cursor = &v
}
return limit, cursor, nil
}
@@ -0,0 +1,23 @@
package handler
import (
"net/http"
"github.com/gin-gonic/gin"
"high-loud-apps-labs/internal/httpapi/dto"
)
type HealthHandler struct{}
func NewHealthHandler() *HealthHandler {
return &HealthHandler{}
}
func (h *HealthHandler) Live(c *gin.Context) {
c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"})
}
func (h *HealthHandler) Ready(c *gin.Context) {
c.JSON(http.StatusOK, dto.HealthResponse{Status: "ok"})
}
@@ -0,0 +1,68 @@
package handler
import (
"net/http"
"github.com/gin-gonic/gin"
"high-loud-apps-labs/internal/httpapi/dto"
"high-loud-apps-labs/internal/httpapi/middleware"
"high-loud-apps-labs/internal/service"
)
type MessageHandler struct {
messages *service.MessageService
}
func NewMessageHandler(messages *service.MessageService) *MessageHandler {
return &MessageHandler{messages: messages}
}
func (h *MessageHandler) Create(c *gin.Context) {
var req dto.CreateMessageRequest
if err := bindStrictJSON(c, &req); err != nil {
respondError(c, err)
return
}
me := middleware.CurrentUser(c)
chatID, err := parseUUIDPathParam(c, "chat_id")
if err != nil {
respondError(c, err)
return
}
m, err := h.messages.Create(c.Request.Context(), me.ID, chatID, req.Text)
if err != nil {
respondError(c, err)
return
}
c.JSON(http.StatusCreated, dto.MessageFromDomain(m))
}
func (h *MessageHandler) List(c *gin.Context) {
me := middleware.CurrentUser(c)
chatID, err := parseUUIDPathParam(c, "chat_id")
if err != nil {
respondError(c, err)
return
}
limit, cursor, err := parseListQuery(c)
if err != nil {
respondError(c, err)
return
}
items, next, err := h.messages.List(c.Request.Context(), me.ID, chatID, limit, cursor)
if err != nil {
respondError(c, err)
return
}
c.JSON(http.StatusOK, dto.MessagePageResponse{
Items: dto.MessagesFromDomain(items),
NextCursor: next,
})
}
@@ -0,0 +1,35 @@
package handler
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/httpapi/dto"
"high-loud-apps-labs/internal/httpapi/middleware"
)
type badRequestError struct{ msg string }
func (e *badRequestError) Error() string { return e.msg }
func (e *badRequestError) Unwrap() error { return domain.ErrInvalidInput }
func (e *badRequestError) Code() domain.ErrorCode { return domain.CodeInvalidRequest }
func parseUUIDPathParam(c *gin.Context, name string) (string, error) {
raw := c.Param(name)
if raw == "" {
return "", &badRequestError{msg: "параметр " + name + " обязателен"}
}
id, err := uuid.Parse(raw)
if err != nil {
return "", &badRequestError{msg: "параметр " + name + " должен быть корректным UUID"}
}
return id.String(), nil
}
func respondError(c *gin.Context, err error) {
reqID := middleware.GetRequestID(c)
c.JSON(dto.StatusFromError(err), dto.ErrorFromDomain(err, reqID))
}
+43
View File
@@ -0,0 +1,43 @@
package handler
import (
"net/http"
"github.com/gin-gonic/gin"
"high-loud-apps-labs/internal/httpapi/dto"
"high-loud-apps-labs/internal/httpapi/middleware"
"high-loud-apps-labs/internal/service"
)
type UserHandler struct {
users *service.UserService
}
func NewUserHandler(users *service.UserService) *UserHandler {
return &UserHandler{users: users}
}
func (h *UserHandler) Create(c *gin.Context) {
var req dto.CreateUserRequest
if err := bindStrictJSON(c, &req); err != nil {
respondError(c, err)
return
}
u, err := h.users.Create(c.Request.Context(), req.Username, req.DisplayName)
if err != nil {
respondError(c, err)
return
}
c.JSON(http.StatusCreated, dto.UserFromDomain(u))
}
func (h *UserHandler) Current(c *gin.Context) {
u := middleware.CurrentUser(c)
if u == nil {
respondError(c, &badRequestError{msg: "нет текущего пользователя"})
return
}
c.JSON(http.StatusOK, dto.UserFromDomain(u))
}
@@ -0,0 +1,49 @@
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"high-loud-apps-labs/internal/domain"
"high-loud-apps-labs/internal/httpapi/dto"
)
const CurrentUserKey = "current_user"
func Auth(users domain.UserRepository) gin.HandlerFunc {
return func(c *gin.Context) {
id := c.GetHeader("X-User-Id")
if id == "" {
abortUnauthorized(c, "требуется X-User-Id")
return
}
u, err := users.GetByID(c.Request.Context(), id)
if err != nil {
abortUnauthorized(c, "неизвестный пользователь")
return
}
c.Set(CurrentUserKey, u)
c.Next()
}
}
func CurrentUser(c *gin.Context) *domain.User {
if v, ok := c.Get(CurrentUserKey); ok {
if u, ok := v.(*domain.User); ok {
return u
}
}
return nil
}
func abortUnauthorized(c *gin.Context, msg string) {
reqID := GetRequestID(c)
body := dto.ErrorFromDomain(
&domain.ForbiddenError{Reason: msg},
reqID,
)
c.AbortWithStatusJSON(http.StatusUnauthorized, body)
}
@@ -0,0 +1,32 @@
package middleware
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
const (
RequestIDKey = "request_id"
RequestIDHeader = "X-Request-Id"
)
func RequestID() gin.HandlerFunc {
return func(c *gin.Context) {
id := c.GetHeader(RequestIDHeader)
if id == "" {
id = uuid.NewString()
}
c.Set(RequestIDKey, id)
c.Writer.Header().Set(RequestIDHeader, id)
c.Next()
}
}
func GetRequestID(c *gin.Context) string {
if v, ok := c.Get(RequestIDKey); ok {
if s, ok := v.(string); ok {
return s
}
}
return ""
}
+45
View File
@@ -0,0 +1,45 @@
package httpapi
import (
"github.com/gin-gonic/gin"
"high-loud-apps-labs/internal/httpapi/handler"
"high-loud-apps-labs/internal/httpapi/middleware"
)
type Handlers struct {
Health *handler.HealthHandler
User *handler.UserHandler
Chat *handler.ChatHandler
Message *handler.MessageHandler
}
func NewRouter(h Handlers, auth gin.HandlerFunc) *gin.Engine {
gin.EnableJsonDecoderDisallowUnknownFields()
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.Use(middleware.RequestID())
r.GET("/health/live", h.Health.Live)
r.GET("/health/ready", h.Health.Ready)
api := r.Group("/api/v1")
{
api.POST("/users", h.User.Create)
}
protected := api.Group("")
protected.Use(auth)
{
protected.GET("/users/me", h.User.Current)
protected.POST("/chats", h.Chat.Create)
protected.GET("/chats", h.Chat.List)
protected.GET("/chats/:chat_id", h.Chat.Get)
protected.POST("/chats/:chat_id/messages", h.Message.Create)
protected.GET("/chats/:chat_id/messages", h.Message.List)
}
return r
}