Files

64 lines
1.7 KiB
Go

package common
import (
"bytes"
"encoding/json"
"io"
"strings"
"github.com/gofiber/fiber/v3"
)
// ReadBodyLimited reads at most limit bytes from the request body. The caller
// must use it instead of c.Body() when the endpoint has a smaller budget than
// the process-wide Fiber.BodyLimit. The limit itself belongs to the caller
// (config.MaxJSONBodyBytes for JSON endpoints).
//
// with StreamRequestBody enabled fasthttp exposes the network body as a
// stream, so io.ReadAll over a LimitReader allocates only the bytes the
// endpoint actually accepts instead of the whole upload limit.
func ReadBodyLimited(c fiber.Ctx, limit int64) ([]byte, error) {
var reader io.Reader = c.Request().BodyStream()
if reader == nil {
reader = bytes.NewReader(c.Body())
}
data, err := io.ReadAll(io.LimitReader(reader, limit+1))
if err != nil {
return nil, BadRequest("incomplete request body")
}
if int64(len(data)) > limit {
return nil, PayloadTooLarge("request body is too large")
}
return data, nil
}
func BindJSON(c fiber.Ctx, dst any, limit int64) error {
if contentType := c.Get(fiber.HeaderContentType); !strings.HasPrefix(contentType, "application/json") {
return UnsupportedMedia("invalid JSON body")
}
body, err := ReadBodyLimited(c, limit)
if err != nil {
return err
}
if len(body) == 0 {
return BadRequest("request body is empty")
}
decoder := json.NewDecoder(bytes.NewReader(body))
decoder.DisallowUnknownFields()
if err := decoder.Decode(dst); err != nil {
return BadRequest("invalid JSON body")
}
var extra json.RawMessage
if err := decoder.Decode(&extra); err != io.EOF {
return BadRequest("request body has extra trailing bytes")
}
return nil
}