forked from mtusi2026/mtusi2026lab2
refactor(app) AI refactoring before moving to Lab3 done
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
// AGENT: Field-level validation is deliberately not delegated to a generic
|
||||
// struct validator. The contract needs specific messages for blank strings,
|
||||
// Unicode length and duplicate member IDs, so handlers call the Validators in
|
||||
// validation.go after this strict JSON decoding step.
|
||||
//
|
||||
// BindJSON enforces the request format from the contract: JSON content type,
|
||||
// exactly one JSON value, no unknown fields and correct Go types. Field-level
|
||||
// rules (non-blank strings, lengths, UUID lists) stay in the handlers so their
|
||||
// messages can be specific.
|
||||
func BindJSON(c fiber.Ctx, dst any) error {
|
||||
if contentType := c.Get(fiber.HeaderContentType); !strings.HasPrefix(contentType, "application/json") {
|
||||
return UnsupportedMedia("invalid JSON body")
|
||||
}
|
||||
|
||||
body := c.Body()
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user