forked from mtusi2026/mtusi2026lab5
ЛР 5: асинхронная обработка изображений, уровень 5
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
)
|
||||
|
||||
// routeUploadAttachment освобождён от общего лимита тела: свой лимит применяется в сервисе, после
|
||||
// аутентификации и проверки доступа.
|
||||
const routeUploadAttachment = "/api/v1/chats/:chat_id/attachments"
|
||||
|
||||
// transferTimeout — предел на передачу одного файла. Общие таймауты сервера (10 с) рассчитаны на
|
||||
// JSON и оборвали бы загрузку 10 МиБ на медленном канале. Предел обязателен: иначе медленный клиент
|
||||
// занимал бы слот загрузки неограниченно долго.
|
||||
const transferTimeout = 60 * time.Second
|
||||
|
||||
type attachmentsHandler struct {
|
||||
attachments service.AttachmentsService
|
||||
}
|
||||
|
||||
// rejectedBodyDrainLimit — сколько байт отклонённой загрузки дочитывается впустую. Клиент обычно
|
||||
// сначала отправляет всё тело и только потом читает ответ: если перестать читать, он зависнет и
|
||||
// вместо 413 получит обрыв. Дочитывание идёт в никуда, поэтому память не расходует, а его время
|
||||
// ограничено transferTimeout. Тело больше этого предела приводит к закрытию соединения.
|
||||
const rejectedBodyDrainLimit = 64 << 20
|
||||
|
||||
func extendDeadlines(c echo.Context) {
|
||||
rc := http.NewResponseController(c.Response())
|
||||
deadline := time.Now().Add(transferTimeout)
|
||||
// Ошибка значит, что соединение не поддерживает дедлайны: тогда действуют общие таймауты.
|
||||
_ = rc.SetReadDeadline(deadline)
|
||||
_ = rc.SetWriteDeadline(deadline)
|
||||
}
|
||||
|
||||
// uploadTransfer стоит снаружи аутентификации, поэтому покрывает и отказы 401. Небольшой ответ об
|
||||
// ошибке остаётся в буфере сервера и уходит клиенту после дочитывания.
|
||||
func uploadTransfer(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
extendDeadlines(c)
|
||||
err := next(c)
|
||||
_, _ = io.CopyN(io.Discard, c.Request().Body, rejectedBodyDrainLimit)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (h *attachmentsHandler) upload(c echo.Context) error {
|
||||
req := c.Request()
|
||||
// Несколько filename неоднозначны: пустое значение сервис отклонит как неверное имя.
|
||||
var filename string
|
||||
if values := c.QueryParams()["filename"]; len(values) == 1 {
|
||||
filename = values[0]
|
||||
}
|
||||
att, err := h.attachments.Upload(req.Context(), service.UploadInput{
|
||||
CallerID: c.Get(middleware.AuthUserIDKey).(string),
|
||||
ChatID: c.Param("chat_id"),
|
||||
Filename: filename,
|
||||
ContentType: req.Header.Get(echo.HeaderContentType),
|
||||
ContentLength: req.ContentLength,
|
||||
Body: req.Body,
|
||||
})
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusAccepted, toAttachmentResponse(att))
|
||||
}
|
||||
|
||||
func (h *attachmentsHandler) get(c echo.Context) error {
|
||||
att, err := h.attachments.Get(c.Request().Context(), c.Get(middleware.AuthUserIDKey).(string), c.Param("attachment_id"))
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toAttachmentResponse(att))
|
||||
}
|
||||
|
||||
func (h *attachmentsHandler) content(c echo.Context) error {
|
||||
extendDeadlines(c)
|
||||
variant := service.VariantOriginal
|
||||
if values, ok := c.QueryParams()["variant"]; ok {
|
||||
variant = values[0]
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(c.Request().Context(), transferTimeout)
|
||||
defer cancel()
|
||||
|
||||
att, body, err := h.attachments.Content(ctx, c.Get(middleware.AuthUserIDKey).(string), c.Param("attachment_id"), variant)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
header := c.Response().Header()
|
||||
header.Set(echo.HeaderContentLength, strconv.FormatInt(att.SizeBytes, 10))
|
||||
// Файл загрузил пользователь: браузер не должен угадывать тип или показывать его как страницу.
|
||||
header.Set("X-Content-Type-Options", "nosniff")
|
||||
header.Set("Cache-Control", "private, no-store")
|
||||
if cd := mime.FormatMediaType("attachment", map[string]string{"filename": att.Filename}); cd != "" {
|
||||
header.Set(echo.HeaderContentDisposition, cd)
|
||||
} else {
|
||||
header.Set(echo.HeaderContentDisposition, "attachment")
|
||||
}
|
||||
// Обрыв после начала передачи клиент увидит как неполный ответ: длина объявлена заранее.
|
||||
return c.Stream(http.StatusOK, att.ContentType, body)
|
||||
}
|
||||
|
||||
func toAttachmentResponse(a domain.Attachment) dto.AttachmentResponse {
|
||||
return dto.AttachmentResponse{
|
||||
ID: a.ID,
|
||||
ChatID: a.ChatID,
|
||||
OwnerID: a.OwnerID,
|
||||
Filename: a.Filename,
|
||||
ContentType: a.ContentType,
|
||||
SizeBytes: a.SizeBytes,
|
||||
SHA256: a.SHA256,
|
||||
Status: a.Status,
|
||||
Variants: attachmentVariants(a),
|
||||
ErrorCode: a.ErrorCode,
|
||||
CreatedAt: dto.NewTimestamp(a.CreatedAt),
|
||||
UpdatedAt: dto.NewTimestamp(a.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func attachmentVariants(a domain.Attachment) []dto.VariantResponse {
|
||||
v := []dto.VariantResponse{}
|
||||
if a.Status == domain.StatusReady {
|
||||
for _, t := range a.Variants {
|
||||
v = append(v, dto.VariantResponse{Name: t.Name, ContentType: t.ContentType, SizeBytes: t.SizeBytes, Width: t.Width, Height: t.Height, SHA256: t.SHA256})
|
||||
}
|
||||
}
|
||||
return v
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
type authHandler struct {
|
||||
auth service.AuthService
|
||||
}
|
||||
|
||||
func (h *authHandler) createSession(c echo.Context) error {
|
||||
if c.Request().ContentLength > 0 {
|
||||
return WriteError(c, &validate.Error{Field: "body", Reason: "must be empty, credentials go in Authorization: Basic"})
|
||||
}
|
||||
username, password, ok := parseBasic(c.Request().Header.Get(echo.HeaderAuthorization))
|
||||
if !ok {
|
||||
return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials")
|
||||
}
|
||||
|
||||
s, err := h.auth.Login(c.Request().Context(), username, password)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrUnauthorized) {
|
||||
return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials")
|
||||
}
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, dto.SessionResponse{
|
||||
Token: s.Token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: dto.NewTimestamp(s.ExpiresAt),
|
||||
User: toUserResponse(s.User),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *authHandler) revokeSession(c echo.Context) error {
|
||||
tok := c.Get(middleware.AuthTokenKey).(string)
|
||||
if err := h.auth.Logout(c.Request().Context(), tok); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.NoContent(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func parseBasic(header string) (username, password string, ok bool) {
|
||||
scheme, encoded, found := strings.Cut(header, " ")
|
||||
if !found || !strings.EqualFold(scheme, "Basic") {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded))
|
||||
if err != nil || !utf8.Valid(raw) {
|
||||
return "", "", false
|
||||
}
|
||||
username, password, found = strings.Cut(string(raw), ":")
|
||||
if !found || username == "" || password == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return username, password, true
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
type chatsHandler struct {
|
||||
chats service.ChatsService
|
||||
}
|
||||
|
||||
func (h *chatsHandler) create(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
var req dto.CreateChatRequest
|
||||
if err := decodeJSON(c.Request().Body, &req); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
chat, err := h.chats.Create(c.Request().Context(), callerID, req.Title, req.MemberIDs)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *chatsHandler) get(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
chatID := c.Param("chat_id")
|
||||
|
||||
chat, err := h.chats.Get(c.Request().Context(), callerID, chatID)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toChatResponse(chat))
|
||||
}
|
||||
|
||||
func (h *chatsHandler) list(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
limit, cursor, err := parsePageParams(c)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
page, err := h.chats.List(c.Request().Context(), callerID, cursor, limit)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toChatsPage(page))
|
||||
}
|
||||
|
||||
func toChatResponse(ch domain.Chat) dto.ChatResponse {
|
||||
members := make([]string, len(ch.MemberIDs))
|
||||
copy(members, ch.MemberIDs)
|
||||
return dto.ChatResponse{
|
||||
ID: ch.ID,
|
||||
Title: ch.Title,
|
||||
MemberIDs: members,
|
||||
CreatedAt: dto.NewTimestamp(ch.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func toChatsPage(p domain.Page[domain.Chat]) dto.ChatsPageResponse {
|
||||
items := make([]dto.ChatResponse, 0, len(p.Items))
|
||||
for _, ch := range p.Items {
|
||||
items = append(items, toChatResponse(ch))
|
||||
}
|
||||
var next *string
|
||||
if p.NextCursor != "" {
|
||||
s := p.NextCursor
|
||||
next = &s
|
||||
}
|
||||
return dto.ChatsPageResponse{Items: items, NextCursor: next}
|
||||
}
|
||||
|
||||
func parsePageParams(c echo.Context) (int, string, error) {
|
||||
q := c.QueryParams()
|
||||
|
||||
limit := validate.LimitDefault
|
||||
if vals, ok := q["limit"]; ok {
|
||||
n, err := strconv.Atoi(vals[0])
|
||||
if err != nil {
|
||||
return 0, "", &validate.Error{Field: "limit", Reason: "must be an integer"}
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
|
||||
cursor := ""
|
||||
if vals, ok := q["cursor"]; ok {
|
||||
if vals[0] == "" {
|
||||
return 0, "", &validate.Error{Field: "cursor", Reason: "must not be empty"}
|
||||
}
|
||||
cursor = vals[0]
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package dto
|
||||
|
||||
// VariantResponse — преобразованная копия. В lab4 вариантов нет, список всегда пуст.
|
||||
type VariantResponse struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
// AttachmentResponse намеренно не содержит object key: он внутренний.
|
||||
type AttachmentResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []VariantResponse `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
UpdatedAt Timestamp `json:"updated_at"`
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package dto
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type ChatResponse struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
|
||||
type ChatsPageResponse struct {
|
||||
Items []ChatResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package dto
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// AttachmentIDList — необязательное поле: отсутствие равно [], но явный null по контракту неверен.
|
||||
// Обычный срез принял бы null молча, поэтому разбор свой.
|
||||
type AttachmentIDList []string
|
||||
|
||||
func (l *AttachmentIDList) UnmarshalJSON(data []byte) error {
|
||||
if string(data) == "null" {
|
||||
return errors.New("attachment_ids must be an array")
|
||||
}
|
||||
return json.Unmarshal(data, (*[]string)(l))
|
||||
}
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
// Text — указатель: поле обязательно и при наличии вложений, а "" допустим только с ними.
|
||||
Text *string `json:"text"`
|
||||
AttachmentIDs AttachmentIDList `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type MessageResponse struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type MessagesPageResponse struct {
|
||||
Items []MessageResponse `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package dto
|
||||
|
||||
import "time"
|
||||
|
||||
const timestampLayout = "2006-01-02T15:04:05.000000Z"
|
||||
|
||||
// Timestamp сериализуется в UTC всегда с 6 цифрами дробной части. Стандартный формат
|
||||
// time.Time отбрасывает нули в конце (…17.95188Z): это корректный RFC 3339, но такое значение
|
||||
// не разбирает datetime.fromisoformat в Python 3.9–3.10, на которых идут публичные тесты.
|
||||
type Timestamp struct {
|
||||
time.Time
|
||||
}
|
||||
|
||||
func NewTimestamp(t time.Time) Timestamp {
|
||||
return Timestamp{Time: t}
|
||||
}
|
||||
|
||||
func (t Timestamp) MarshalJSON() ([]byte, error) {
|
||||
return []byte(`"` + t.UTC().Format(timestampLayout) + `"`), nil
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package dto
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type UserResponse struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt Timestamp `json:"created_at"`
|
||||
}
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt Timestamp `json:"expires_at"`
|
||||
User UserResponse `json:"user"`
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const (
|
||||
CodeInvalidRequest = "invalid_request"
|
||||
CodeUnauthorized = "unauthorized"
|
||||
CodeNotFound = "not_found"
|
||||
CodeConflict = "conflict"
|
||||
CodePayloadTooLarge = "payload_too_large"
|
||||
CodeUnsupportedMedia = "unsupported_media_type"
|
||||
CodeRateLimited = "rate_limited"
|
||||
CodeUnavailable = "unavailable"
|
||||
CodeInternalError = "internal_error"
|
||||
)
|
||||
|
||||
type errorBody struct {
|
||||
Error errorPayload `json:"error"`
|
||||
}
|
||||
|
||||
type errorPayload struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
var (
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
ErrUnsupportedMedia = errors.New("unsupported media type")
|
||||
)
|
||||
|
||||
func Classify(err error) (status int, code, message string) {
|
||||
switch {
|
||||
case errors.Is(err, domain.ErrIdempotencyConflict):
|
||||
return http.StatusConflict, CodeConflict, "Idempotency-Key was already used with a different request"
|
||||
case errors.Is(err, domain.ErrNotFound):
|
||||
return http.StatusNotFound, CodeNotFound, "Object not found"
|
||||
case errors.Is(err, domain.ErrConflict):
|
||||
return http.StatusConflict, CodeConflict, "Resource already exists"
|
||||
case errors.Is(err, domain.ErrInvalidArgument):
|
||||
return http.StatusBadRequest, CodeInvalidRequest, "Invalid request arguments"
|
||||
case errors.Is(err, domain.ErrUnavailable):
|
||||
return http.StatusServiceUnavailable, CodeUnavailable, "Service temporarily unavailable"
|
||||
case errors.Is(err, domain.ErrPayloadTooLarge):
|
||||
return http.StatusRequestEntityTooLarge, CodePayloadTooLarge, "Request body too large"
|
||||
case errors.Is(err, domain.ErrRateLimited):
|
||||
return http.StatusTooManyRequests, CodeRateLimited, "Too many concurrent requests"
|
||||
case errors.Is(err, ErrUnauthorized), errors.Is(err, domain.ErrUnauthorized):
|
||||
return http.StatusUnauthorized, CodeUnauthorized, "Identification required"
|
||||
case errors.Is(err, domain.ErrUnsupportedMedia):
|
||||
return http.StatusUnsupportedMediaType, CodeUnsupportedMedia, "Expected a valid PNG or JPEG image"
|
||||
case errors.Is(err, ErrUnsupportedMedia):
|
||||
return http.StatusUnsupportedMediaType, CodeUnsupportedMedia, "Expected Content-Type: application/json"
|
||||
}
|
||||
|
||||
var vErr *validate.Error
|
||||
if errors.As(err, &vErr) {
|
||||
return http.StatusBadRequest, CodeInvalidRequest, vErr.Error()
|
||||
}
|
||||
|
||||
return http.StatusInternalServerError, CodeInternalError, "Internal server error"
|
||||
}
|
||||
|
||||
func WriteError(c echo.Context, err error) error {
|
||||
status, code, msg := Classify(err)
|
||||
if status == http.StatusTooManyRequests {
|
||||
c.Response().Header().Set("Retry-After", "1")
|
||||
}
|
||||
return c.JSON(status, errorBody{
|
||||
Error: errorPayload{
|
||||
Code: code,
|
||||
Message: msg,
|
||||
RequestID: c.Response().Header().Get(echo.HeaderXRequestID),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func healthLive(c echo.Context) error {
|
||||
return c.JSON(http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
func healthReady(isReady func() bool) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !isReady() {
|
||||
return echo.NewHTTPError(http.StatusServiceUnavailable, "Service unavailable")
|
||||
}
|
||||
return c.JSON(http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
const headerIdempotencyKey = "Idempotency-Key"
|
||||
|
||||
type messagesHandler struct {
|
||||
messages service.MessagesService
|
||||
}
|
||||
|
||||
func (h *messagesHandler) send(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
chatID := c.Param("chat_id")
|
||||
|
||||
var req dto.CreateMessageRequest
|
||||
if err := decodeJSON(c.Request().Body, &req); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
if req.Text == nil {
|
||||
return WriteError(c, &validate.Error{Field: "text", Reason: "is required"})
|
||||
}
|
||||
|
||||
msg, err := h.messages.Send(c.Request().Context(), callerID, chatID, c.Request().Header.Get(headerIdempotencyKey), *req.Text, req.AttachmentIDs)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, toMessageResponse(msg))
|
||||
}
|
||||
|
||||
func (h *messagesHandler) list(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
chatID := c.Param("chat_id")
|
||||
|
||||
limit, cursor, err := parsePageParams(c)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
page, err := h.messages.List(c.Request().Context(), callerID, chatID, cursor, limit)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toMessagesPage(page))
|
||||
}
|
||||
|
||||
func toMessageResponse(m domain.Message) dto.MessageResponse {
|
||||
return dto.MessageResponse{
|
||||
ID: m.ID,
|
||||
ChatID: m.ChatID,
|
||||
SenderID: m.AuthorID,
|
||||
Text: m.Text,
|
||||
CreatedAt: dto.NewTimestamp(m.CreatedAt),
|
||||
// Без вложений в JSON должен быть [], а не null.
|
||||
AttachmentIDs: append([]string{}, m.AttachmentIDs...),
|
||||
}
|
||||
}
|
||||
|
||||
func toMessagesPage(p domain.Page[domain.Message]) dto.MessagesPageResponse {
|
||||
items := make([]dto.MessageResponse, 0, len(p.Items))
|
||||
for _, m := range p.Items {
|
||||
items = append(items, toMessageResponse(m))
|
||||
}
|
||||
var next *string
|
||||
if p.NextCursor != "" {
|
||||
s := p.NextCursor
|
||||
next = &s
|
||||
}
|
||||
return dto.MessagesPageResponse{Items: items, NextCursor: next}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const AuthTokenKey = "auth_token"
|
||||
|
||||
const (
|
||||
BearerChallenge = `Bearer realm="messenger"`
|
||||
BasicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
)
|
||||
|
||||
type Authenticator interface {
|
||||
Authenticate(ctx context.Context, token string) (userID string, err error)
|
||||
}
|
||||
|
||||
func Bearer(auth Authenticator) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
tok, ok := BearerToken(c.Request().Header.Get(echo.HeaderAuthorization))
|
||||
if !ok {
|
||||
return unauthorized(c, BearerChallenge, "Bearer token required")
|
||||
}
|
||||
userID, err := auth.Authenticate(c.Request().Context(), tok)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrUnauthorized) {
|
||||
return unauthorized(c, BearerChallenge, "Invalid or expired session")
|
||||
}
|
||||
return err
|
||||
}
|
||||
c.Set(AuthUserIDKey, userID)
|
||||
c.Set(AuthTokenKey, tok)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BearerToken(header string) (string, bool) {
|
||||
scheme, tok, found := strings.Cut(header, " ")
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") {
|
||||
return "", false
|
||||
}
|
||||
tok = strings.TrimSpace(tok)
|
||||
return tok, tok != ""
|
||||
}
|
||||
|
||||
func unauthorized(c echo.Context, challenge, msg string) error {
|
||||
c.Response().Header().Set(echo.HeaderWWWAuthenticate, challenge)
|
||||
return echo.NewHTTPError(http.StatusUnauthorized, msg)
|
||||
}
|
||||
|
||||
func Unauthorized(c echo.Context, challenge, msg string) error {
|
||||
return unauthorized(c, challenge, msg)
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func ContentType() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !methodHasBody(c.Request().Method) {
|
||||
return next(c)
|
||||
}
|
||||
if !isApplicationJSON(c.Request().Header.Get(echo.HeaderContentType)) {
|
||||
return echo.NewHTTPError(http.StatusUnsupportedMediaType, "Expected Content-Type: application/json")
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func methodHasBody(method string) bool {
|
||||
switch method {
|
||||
case http.MethodPost, http.MethodPut, http.MethodPatch:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isApplicationJSON(ct string) bool {
|
||||
if ct == "" {
|
||||
return false
|
||||
}
|
||||
mediatype, _, err := mime.ParseMediaType(ct)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return strings.EqualFold(mediatype, "application/json")
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package middleware
|
||||
|
||||
import "github.com/labstack/echo/v4"
|
||||
|
||||
const HeaderInstanceID = "X-Instance-Id"
|
||||
|
||||
func InstanceID(id string) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
c.Response().Header().Set(HeaderInstanceID, id)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"io"
|
||||
"runtime"
|
||||
"slices"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
)
|
||||
|
||||
// BodyLimit ограничивает тело запроса. Маршруты из exemptRoutes применяют собственный лимит.
|
||||
func BodyLimit(maxBytes int64, exemptRoutes ...string) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !methodHasBody(c.Request().Method) || slices.Contains(exemptRoutes, c.Path()) {
|
||||
return next(c)
|
||||
}
|
||||
if cl := c.Request().ContentLength; cl > maxBytes {
|
||||
return domain.ErrPayloadTooLarge
|
||||
}
|
||||
c.Request().Body = &limitedBody{
|
||||
raw: c.Request().Body,
|
||||
maxLeft: maxBytes,
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type limitedBody struct {
|
||||
raw io.ReadCloser
|
||||
maxLeft int64
|
||||
}
|
||||
|
||||
func (b *limitedBody) Read(p []byte) (int, error) {
|
||||
if int64(len(p)) > b.maxLeft+1 {
|
||||
p = p[:b.maxLeft+1]
|
||||
}
|
||||
n, err := b.raw.Read(p)
|
||||
b.maxLeft -= int64(n)
|
||||
if b.maxLeft < 0 {
|
||||
return n, domain.ErrPayloadTooLarge
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (b *limitedBody) Close() error {
|
||||
return b.raw.Close()
|
||||
}
|
||||
|
||||
func InFlight(maxInFlight int) echo.MiddlewareFunc {
|
||||
sem := make(chan struct{}, maxInFlight)
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if isHealthPath(c.Request().URL.Path) {
|
||||
return next(c)
|
||||
}
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
defer func() { <-sem }()
|
||||
return next(c)
|
||||
default:
|
||||
return domain.ErrRateLimited
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func MemoryGuard(maxHeapBytes uint64, poll time.Duration) echo.MiddlewareFunc {
|
||||
var sample atomic.Uint64
|
||||
|
||||
readOnce := func() {
|
||||
var m runtime.MemStats
|
||||
runtime.ReadMemStats(&m)
|
||||
if m.HeapInuse > maxHeapBytes {
|
||||
runtime.GC()
|
||||
runtime.ReadMemStats(&m)
|
||||
}
|
||||
sample.Store(m.HeapInuse)
|
||||
}
|
||||
readOnce()
|
||||
|
||||
if poll > 0 {
|
||||
go func() {
|
||||
t := time.NewTicker(poll)
|
||||
defer t.Stop()
|
||||
for range t.C {
|
||||
readOnce()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
if !methodHasBody(c.Request().Method) || isHealthPath(c.Request().URL.Path) {
|
||||
return next(c)
|
||||
}
|
||||
if sample.Load() > maxHeapBytes {
|
||||
return domain.ErrUnavailable
|
||||
}
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isHealthPath(path string) bool {
|
||||
return path == "/health/live" || path == "/health/ready"
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const AuthUserIDKey = "caller_id"
|
||||
|
||||
func Logger(logger *slog.Logger) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
start := time.Now()
|
||||
if err := next(c); err != nil {
|
||||
c.Error(err)
|
||||
}
|
||||
status := c.Response().Status
|
||||
|
||||
rid, _ := c.Get(RequestIDKey).(string)
|
||||
uid, _ := c.Get(AuthUserIDKey).(string)
|
||||
|
||||
attrs := []slog.Attr{
|
||||
slog.String("request_id", rid),
|
||||
slog.String("method", c.Request().Method),
|
||||
slog.String("path", c.Request().URL.Path),
|
||||
slog.Int("status", status),
|
||||
slog.Int64("duration_ms", time.Since(start).Milliseconds()),
|
||||
slog.String("remote_ip", c.RealIP()),
|
||||
}
|
||||
if uid != "" {
|
||||
attrs = append(attrs, slog.String("user_id", uid))
|
||||
}
|
||||
|
||||
level := slog.LevelInfo
|
||||
switch {
|
||||
case status >= 500:
|
||||
level = slog.LevelError
|
||||
case status >= 400:
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
logger.LogAttrs(c.Request().Context(), level, "http request", attrs...)
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
func Recover(logger *slog.Logger) echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) (err error) {
|
||||
defer func() {
|
||||
r := recover()
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
rid, _ := c.Get(RequestIDKey).(string)
|
||||
logger.Error("panic recovered",
|
||||
slog.String("request_id", rid),
|
||||
slog.String("method", c.Request().Method),
|
||||
slog.String("path", c.Request().URL.Path),
|
||||
slog.Any("panic", r),
|
||||
slog.String("stack", string(debug.Stack())),
|
||||
)
|
||||
err = echo.NewHTTPError(http.StatusInternalServerError, "Internal server error")
|
||||
}()
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/google/uuid"
|
||||
"github.com/labstack/echo/v4"
|
||||
)
|
||||
|
||||
const RequestIDKey = "request_id"
|
||||
|
||||
func RequestID() echo.MiddlewareFunc {
|
||||
return func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
rid := c.Request().Header.Get(echo.HeaderXRequestID)
|
||||
if rid == "" {
|
||||
rid = uuid.NewString()
|
||||
}
|
||||
c.Response().Header().Set(echo.HeaderXRequestID, rid)
|
||||
c.Set(RequestIDKey, rid)
|
||||
return next(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
)
|
||||
|
||||
func registerRoutes(e *echo.Echo, d Deps, isReady func() bool) {
|
||||
e.GET("/health/live", healthLive)
|
||||
e.GET("/health/ready", healthReady(isReady))
|
||||
|
||||
usersH := &usersHandler{users: d.Users}
|
||||
chatsH := &chatsHandler{chats: d.Chats}
|
||||
messagesH := &messagesHandler{messages: d.Messages}
|
||||
authH := &authHandler{auth: d.Auth}
|
||||
attachmentsH := &attachmentsHandler{attachments: d.Attachments}
|
||||
|
||||
auth := middleware.Bearer(d.Auth)
|
||||
|
||||
jsonBody := middleware.ContentType()
|
||||
|
||||
v1 := e.Group("/api/v1")
|
||||
v1.POST("/users", usersH.create, jsonBody)
|
||||
v1.POST("/auth/sessions", authH.createSession)
|
||||
v1.DELETE("/auth/sessions/current", authH.revokeSession, auth)
|
||||
v1.GET("/users/me", usersH.me, auth)
|
||||
v1.POST("/chats", chatsH.create, auth, jsonBody)
|
||||
v1.GET("/chats", chatsH.list, auth)
|
||||
v1.GET("/chats/:chat_id", chatsH.get, auth)
|
||||
v1.POST("/chats/:chat_id/messages", messagesH.send, auth, jsonBody)
|
||||
v1.GET("/chats/:chat_id/messages", messagesH.list, auth)
|
||||
// Тело здесь не JSON: Content-Type и размер проверяет сервис, после проверки доступа.
|
||||
v1.POST("/chats/:chat_id/attachments", attachmentsH.upload, uploadTransfer, auth)
|
||||
v1.GET("/attachments/:attachment_id", attachmentsH.get, auth)
|
||||
v1.GET("/attachments/:attachment_id/content", attachmentsH.content, auth)
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
nethttp "net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
|
||||
)
|
||||
|
||||
type Deps struct {
|
||||
Config *config.Config
|
||||
Logger *slog.Logger
|
||||
Store store.Store
|
||||
Auth service.AuthService
|
||||
Users service.UsersService
|
||||
Chats service.ChatsService
|
||||
Messages service.MessagesService
|
||||
Attachments service.AttachmentsService
|
||||
|
||||
Ready func(ctx context.Context) error
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
e *echo.Echo
|
||||
cfg config.HTTP
|
||||
logger *slog.Logger
|
||||
shutting atomic.Bool
|
||||
ready func(ctx context.Context) error
|
||||
}
|
||||
|
||||
func NewServer(d Deps) *Server {
|
||||
s := &Server{
|
||||
e: echo.New(),
|
||||
cfg: d.Config.HTTP,
|
||||
logger: d.Logger,
|
||||
ready: d.Ready,
|
||||
}
|
||||
|
||||
s.e.HideBanner = true
|
||||
s.e.HidePort = true
|
||||
s.e.HTTPErrorHandler = s.httpErrorHandler
|
||||
|
||||
s.e.Server.ReadTimeout = time.Duration(s.cfg.ReadTimeoutMs) * time.Millisecond
|
||||
s.e.Server.WriteTimeout = time.Duration(s.cfg.WriteTimeoutMs) * time.Millisecond
|
||||
s.e.Server.IdleTimeout = time.Duration(s.cfg.IdleTimeoutMs) * time.Millisecond
|
||||
|
||||
s.e.Use(middleware.InstanceID(d.Config.InstanceID))
|
||||
s.e.Use(middleware.Recover(d.Logger))
|
||||
s.e.Use(middleware.RequestID())
|
||||
s.e.Use(middleware.Logger(d.Logger))
|
||||
s.e.Use(middleware.InFlight(d.Config.Limits.MaxInFlight))
|
||||
s.e.Use(middleware.BodyLimit(d.Config.Limits.MaxBodyBytes, routeUploadAttachment))
|
||||
s.e.Use(middleware.MemoryGuard(d.Config.Limits.MaxHeapBytes, 100*time.Millisecond))
|
||||
|
||||
registerRoutes(s.e, d, s.IsReady)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) Start() error {
|
||||
s.logger.Info("http server starting", slog.String("addr", s.cfg.Addr))
|
||||
err := s.e.Start(s.cfg.Addr)
|
||||
if errors.Is(err, nethttp.ErrServerClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Drain переводит readiness в 503 и ждёт d, продолжая обслуживать запросы: за это время
|
||||
// балансировщик выводит реплику, и новые запросы не попадают на закрытый listener.
|
||||
func (s *Server) Drain(d time.Duration) {
|
||||
s.shutting.Store(true)
|
||||
s.logger.Info("http server draining", slog.Duration("for", d))
|
||||
time.Sleep(d)
|
||||
}
|
||||
|
||||
func (s *Server) Shutdown(ctx context.Context) error {
|
||||
s.shutting.Store(true)
|
||||
s.logger.Info("http server shutting down")
|
||||
return s.e.Shutdown(ctx)
|
||||
}
|
||||
|
||||
func (s *Server) IsReady() bool {
|
||||
if s.shutting.Load() {
|
||||
return false
|
||||
}
|
||||
if s.ready == nil {
|
||||
return true
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), readyTimeout)
|
||||
defer cancel()
|
||||
return s.ready(ctx) == nil
|
||||
}
|
||||
|
||||
const readyTimeout = time.Second
|
||||
|
||||
func (s *Server) Handler() nethttp.Handler {
|
||||
return s.e
|
||||
}
|
||||
|
||||
func (s *Server) httpErrorHandler(err error, c echo.Context) {
|
||||
if c.Response().Committed {
|
||||
return
|
||||
}
|
||||
|
||||
var httpErr *echo.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
code := codeFromStatus(httpErr.Code)
|
||||
msg, _ := httpErr.Message.(string)
|
||||
if msg == "" || msg == nethttp.StatusText(httpErr.Code) {
|
||||
msg = messageFor(httpErr.Code, code)
|
||||
}
|
||||
_ = c.JSON(httpErr.Code, errorBody{
|
||||
Error: errorPayload{
|
||||
Code: code,
|
||||
Message: msg,
|
||||
RequestID: c.Response().Header().Get(echo.HeaderXRequestID),
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
_ = WriteError(c, err)
|
||||
}
|
||||
|
||||
var codesByStatus = map[int]string{
|
||||
nethttp.StatusBadRequest: CodeInvalidRequest,
|
||||
nethttp.StatusUnauthorized: CodeUnauthorized,
|
||||
nethttp.StatusNotFound: CodeNotFound,
|
||||
nethttp.StatusMethodNotAllowed: CodeInvalidRequest,
|
||||
nethttp.StatusConflict: CodeConflict,
|
||||
nethttp.StatusRequestEntityTooLarge: CodePayloadTooLarge,
|
||||
nethttp.StatusUnsupportedMediaType: CodeUnsupportedMedia,
|
||||
nethttp.StatusTooManyRequests: CodeRateLimited,
|
||||
nethttp.StatusServiceUnavailable: CodeUnavailable,
|
||||
}
|
||||
|
||||
func codeFromStatus(status int) string {
|
||||
if c, ok := codesByStatus[status]; ok {
|
||||
return c
|
||||
}
|
||||
return CodeInternalError
|
||||
}
|
||||
|
||||
var messagesByStatus = map[int]string{
|
||||
nethttp.StatusMethodNotAllowed: "Method not allowed",
|
||||
}
|
||||
|
||||
func messageFor(status int, code string) string {
|
||||
if m, ok := messagesByStatus[status]; ok {
|
||||
return m
|
||||
}
|
||||
return defaultMessages[code]
|
||||
}
|
||||
|
||||
var defaultMessages = map[string]string{
|
||||
CodeInvalidRequest: "Invalid request",
|
||||
CodeUnauthorized: "Identification required",
|
||||
CodeNotFound: "Object not found",
|
||||
CodeConflict: "Conflict",
|
||||
CodePayloadTooLarge: "Request body too large",
|
||||
CodeUnsupportedMedia: "Unsupported Content-Type",
|
||||
CodeRateLimited: "Too many requests",
|
||||
CodeUnavailable: "Service unavailable",
|
||||
CodeInternalError: "Internal server error",
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
|
||||
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
|
||||
)
|
||||
|
||||
type usersHandler struct {
|
||||
users service.UsersService
|
||||
}
|
||||
|
||||
func (h *usersHandler) create(c echo.Context) error {
|
||||
var req dto.CreateUserRequest
|
||||
if err := decodeJSON(c.Request().Body, &req); err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
|
||||
user, err := h.users.Register(c.Request().Context(), req.Username, req.DisplayName, req.Password)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusCreated, toUserResponse(user))
|
||||
}
|
||||
|
||||
func (h *usersHandler) me(c echo.Context) error {
|
||||
callerID := c.Get(middleware.AuthUserIDKey).(string)
|
||||
user, err := h.users.Me(c.Request().Context(), callerID)
|
||||
if err != nil {
|
||||
return WriteError(c, err)
|
||||
}
|
||||
return c.JSON(http.StatusOK, toUserResponse(user))
|
||||
}
|
||||
|
||||
func toUserResponse(u domain.User) dto.UserResponse {
|
||||
return dto.UserResponse{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
CreatedAt: dto.NewTimestamp(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func decodeJSON(body io.Reader, dst any) error {
|
||||
data, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrPayloadTooLarge) {
|
||||
return err
|
||||
}
|
||||
return &validate.Error{Field: "body", Reason: "cannot read body"}
|
||||
}
|
||||
if !utf8.Valid(data) {
|
||||
return &validate.Error{Field: "body", Reason: "invalid UTF-8"}
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(data))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return &validate.Error{Field: "body", Reason: jsonErrorReason(err)}
|
||||
}
|
||||
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
|
||||
return &validate.Error{Field: "body", Reason: "unexpected data after JSON object"}
|
||||
}
|
||||
return checkExactKeys(data, dst)
|
||||
}
|
||||
|
||||
func checkExactKeys(data []byte, dst any) error {
|
||||
var obj map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &obj); err != nil {
|
||||
return nil
|
||||
}
|
||||
allowed := make(map[string]struct{})
|
||||
t := reflect.TypeOf(dst).Elem()
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
|
||||
allowed[name] = struct{}{}
|
||||
}
|
||||
for key := range obj {
|
||||
if _, ok := allowed[key]; !ok {
|
||||
return &validate.Error{Field: "body", Reason: fmt.Sprintf("unknown field %q", key)}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func jsonErrorReason(err error) string {
|
||||
if errors.Is(err, io.EOF) {
|
||||
return "empty body"
|
||||
}
|
||||
var typeErr *json.UnmarshalTypeError
|
||||
if errors.As(err, &typeErr) {
|
||||
if typeErr.Field == "" {
|
||||
return "expected a JSON object"
|
||||
}
|
||||
return fmt.Sprintf("field %q: invalid type", typeErr.Field)
|
||||
}
|
||||
if name, ok := strings.CutPrefix(err.Error(), "json: unknown field "); ok {
|
||||
return "unknown field " + name
|
||||
}
|
||||
return "invalid JSON"
|
||||
}
|
||||
Reference in New Issue
Block a user