71 lines
2.4 KiB
Go
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)
|
|
}
|