package infra import ( "encoding/json" "fmt" "io" "net/http" ) // HTTPParseBody decodifica el body JSON de r en dst, limitando la lectura a maxBytes. // Retorna error si el body excede maxBytes, si el JSON es invalido, o si hay error de lectura. func HTTPParseBody(r *http.Request, dst any, maxBytes int64) error { r.Body = http.MaxBytesReader(nil, r.Body, maxBytes) dec := json.NewDecoder(r.Body) dec.DisallowUnknownFields() if err := dec.Decode(dst); err != nil { return fmt.Errorf("parse body: %w", err) } // Verificar que no queda mas data despues del primer objeto JSON if dec.More() { return fmt.Errorf("parse body: request body must contain a single JSON object") } // Consumir el resto para liberar el body io.Copy(io.Discard, r.Body) return nil }