Files
mtusi2026lab7/internal/platform/httpx/decode.go
T
kudesn1k 8054913ef9
Application / e2e (pull_request) Blocked by required conditions
Application / unit (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Перенеси реализацию мессенджера из ЛР 6
Источник — проверенное рабочее дерево ЛР 6 поверх 18878d6, включая изменения после повторного ревью. SHA-256 списка исходных файлов: e45a3d85b41feff1da78dce3f20fd1f4af1c5ee629e6ed703218bc8e21ad58fe.
2026-11-30 10:54:41 +03:00

71 lines
2.4 KiB
Go

package httpx
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"strings"
"unicode/utf8"
"github.com/gin-gonic/gin"
"messenger/internal/platform/apperr"
)
// DecodeJSON reads exactly one JSON object into dst and enforces what gin's
// binding does not: the media type must be application/json (415), invalid
// UTF-8, unknown fields, wrong types, malformed syntax and trailing data are
// 400, an oversized body is 413, and messages never expose Go type names.
func DecodeJSON(c *gin.Context, dst any) error {
mediaType, _, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
if err != nil || mediaType != "application/json" {
return apperr.UnsupportedMedia("Content-Type must be application/json")
}
// The body is already capped by the bodyLimit middleware, so reading it
// whole is bounded.
body, err := io.ReadAll(c.Request.Body)
if err != nil {
return decodeError(err)
}
// encoding/json silently replaces invalid UTF-8 with U+FFFD; the contract
// and RFC 8259 require UTF-8, so such a body is rejected, not repaired.
if !utf8.Valid(body) {
return apperr.Invalid("request body must be valid UTF-8")
}
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return decodeError(err)
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return apperr.Invalid("unexpected data after JSON body")
}
return nil
}
func decodeError(err error) error {
if tooLarge, ok := errors.AsType[*http.MaxBytesError](err); ok {
return apperr.Wrap(apperr.KindPayloadTooLarge, fmt.Sprintf("request body must be at most %d bytes", tooLarge.Limit), err)
}
if errors.Is(err, io.EOF) {
return apperr.Wrap(apperr.KindInvalid, "request body is required", err)
}
if wrongType, ok := errors.AsType[*json.UnmarshalTypeError](err); ok {
if wrongType.Field == "" {
return apperr.Wrap(apperr.KindInvalid, "request body must be a JSON object", err)
}
return apperr.Wrap(apperr.KindInvalid, fmt.Sprintf("field %q has wrong type", wrongType.Field), err)
}
// encoding/json reports unknown fields as a plain error without a type.
const unknownPrefix = "json: unknown field "
if msg := err.Error(); strings.HasPrefix(msg, unknownPrefix) {
field := strings.Trim(strings.TrimPrefix(msg, unknownPrefix), `"`)
return apperr.Wrap(apperr.KindInvalid, fmt.Sprintf("unknown field %q", field), err)
}
return apperr.Wrap(apperr.KindInvalid, "malformed JSON body", err)
}