167 lines
5.0 KiB
Go
167 lines
5.0 KiB
Go
package httputil
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/charawein/mtusi2026lab6/internal/service"
|
|
)
|
|
|
|
// requestIDKey — ключ контекста для X-Request-Id.
|
|
type requestIDKey struct{}
|
|
|
|
// ContextWithRequestID кладёт request_id в контекст. Используется middleware.RequestID.
|
|
func ContextWithRequestID(ctx context.Context, id string) context.Context {
|
|
return context.WithValue(ctx, requestIDKey{}, id)
|
|
}
|
|
|
|
// RequestIDFrom извлекает request_id из контекста.
|
|
func RequestIDFrom(ctx context.Context) string {
|
|
if v, ok := ctx.Value(requestIDKey{}).(string); ok {
|
|
return v
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// userIDKey — ключ контекста для аутентифицированного user_id.
|
|
type userIDKey struct{}
|
|
|
|
// ContextWithUserID кладёт user_id в контекст. Используется middleware.Auth.
|
|
func ContextWithUserID(ctx context.Context, id string) context.Context {
|
|
return context.WithValue(ctx, userIDKey{}, id)
|
|
}
|
|
|
|
// UserIDFromContext извлекает user_id из контекста.
|
|
func UserIDFromContext(ctx context.Context) string {
|
|
if v, ok := ctx.Value(userIDKey{}).(string); ok {
|
|
return v
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// errorBody — формат тела ошибки по contracts/openapi.json.
|
|
type errorBody struct {
|
|
Error errorDetail `json:"error"`
|
|
}
|
|
|
|
type errorDetail struct {
|
|
Code string `json:"code"`
|
|
Message string `json:"message"`
|
|
RequestID string `json:"request_id"`
|
|
}
|
|
|
|
// WriteJSON пишет JSON-ответ с заданным статусом.
|
|
func WriteJSON(w http.ResponseWriter, r *http.Request, status int, v any) {
|
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
w.WriteHeader(status)
|
|
if v == nil {
|
|
return
|
|
}
|
|
if err := json.NewEncoder(w).Encode(v); err != nil {
|
|
slog.Error("failed to encode response", "err", err, "request_id", RequestIDFrom(r.Context()))
|
|
}
|
|
}
|
|
|
|
// WriteError мапит доменную ошибку в HTTP-статус и пишет тело в формате контракта.
|
|
func WriteError(w http.ResponseWriter, r *http.Request, err error) {
|
|
status, code := mapError(err)
|
|
reqID := RequestIDFrom(r.Context())
|
|
if reqID == "" {
|
|
reqID = "missing-request-id"
|
|
}
|
|
body := errorBody{Error: errorDetail{
|
|
Code: code,
|
|
Message: messageFor(code),
|
|
RequestID: reqID,
|
|
}}
|
|
WriteJSON(w, r, status, body)
|
|
}
|
|
|
|
func mapError(err error) (int, string) {
|
|
switch {
|
|
case errors.Is(err, service.ErrInvalidInput):
|
|
return http.StatusBadRequest, "invalid_request"
|
|
case errors.Is(err, service.ErrUnauthorized):
|
|
return http.StatusUnauthorized, "unauthorized"
|
|
case errors.Is(err, service.ErrNotFound):
|
|
return http.StatusNotFound, "not_found"
|
|
case errors.Is(err, service.ErrConflict):
|
|
return http.StatusConflict, "conflict"
|
|
case errors.Is(err, service.ErrUnavailable):
|
|
return http.StatusServiceUnavailable, "unavailable"
|
|
case errors.Is(err, service.ErrPayloadTooLarge):
|
|
return http.StatusRequestEntityTooLarge, "payload_too_large"
|
|
case errors.Is(err, service.ErrUnsupportedMedia):
|
|
return http.StatusUnsupportedMediaType, "unsupported_media_type"
|
|
default:
|
|
return http.StatusInternalServerError, "internal_error"
|
|
}
|
|
}
|
|
|
|
func messageFor(code string) string {
|
|
switch code {
|
|
case "invalid_request":
|
|
return "Неверный запрос"
|
|
case "unauthorized":
|
|
return "Требуется аутентификация"
|
|
case "not_found":
|
|
return "Объект не найден"
|
|
case "conflict":
|
|
return "Конфликт"
|
|
case "internal_error":
|
|
return "Внутренняя ошибка"
|
|
case "unavailable":
|
|
return "Сервис недоступен"
|
|
case "payload_too_large":
|
|
return "Слишком большой файл или изображение"
|
|
case "unsupported_media_type":
|
|
return "Поддерживаются только корректные PNG и JPEG"
|
|
default:
|
|
return "Ошибка"
|
|
}
|
|
}
|
|
|
|
// DecodeJSON парсит тело запроса в v, строго запрещая неизвестные поля.
|
|
func DecodeJSON(r *http.Request, v any) error {
|
|
dec := json.NewDecoder(r.Body)
|
|
dec.DisallowUnknownFields()
|
|
if err := dec.Decode(v); err != nil {
|
|
return service.ErrInvalidInput
|
|
}
|
|
if dec.More() {
|
|
return service.ErrInvalidInput
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ParseLimit читает query-параметр limit с дефолтом и границами по контракту.
|
|
func ParseLimit(r *http.Request) (int, error) {
|
|
s := r.URL.Query().Get("limit")
|
|
if s == "" {
|
|
return 50, nil
|
|
}
|
|
n, err := strconv.Atoi(s)
|
|
if err != nil || n < 1 || n > 100 {
|
|
return 0, service.ErrInvalidInput
|
|
}
|
|
return n, nil
|
|
}
|
|
|
|
// PageResponse — универсальный ответ пагинации.
|
|
type PageResponse struct {
|
|
Items any `json:"items"`
|
|
NextCursor *string `json:"next_cursor"`
|
|
}
|
|
|
|
// NextOrNull превращает пустую строку в nil (для сериализации в null).
|
|
func NextOrNull(s string) *string {
|
|
if s == "" {
|
|
return nil
|
|
}
|
|
return &s
|
|
}
|