Validate unknown fields and request sizes
Validate unknown fields and request sizes
For a small JSON request, enforce a byte budget before decoding. Read at most limit+1 bytes with io.LimitReader, reject oversize input, and then use a Decoder with DisallowUnknownFields for a struct. Decode a second time and require io.EOF to reject trailing values. The example assumes a reader with its own timeout policy.
package main
import ( "bytes" "encoding/json" "errors" "fmt" "io" "strings")
func check(e error) { if e != nil { panic(e) }}
type Request struct { N int `json:"n"`}
func parse(r io.Reader) (Request, error) { var p Request b, e := io.ReadAll(io.LimitReader(r, 65)) if e != nil { return Request{}, e } if len(b) > 64 { return Request{}, errors.New("too large") } d := json.NewDecoder(bytes.NewReader(b)) d.DisallowUnknownFields() if e = d.Decode(&p); e != nil { return Request{}, e } var extra any if e = d.Decode(&extra); e != io.EOF { return Request{}, errors.New("trailing data") } if p.N <= 0 { return Request{}, errors.New("n must be positive") } return p, nil}func main() { for _, s := range []string{`{"n":3}`, `{"n":3,"x":1}`, `{"n":3} {}`, strings.Repeat(" ", 65)} { p, e := parse(strings.NewReader(s)) fmt.Println(p.N, e == nil) }}The extra byte distinguishes exactly 64 bytes from an oversized request. The second Decode allows only end-of-stream (possibly preceded by whitespace). The N check enforces a domain rule. The parser rejects errors before returning data. DisallowUnknownFields is not a complete security policy: it does not reject duplicate keys or all alternate spellings. A real HTTP service also needs body limits and deadlines at the transport boundary.
Expected output:
3 true0 false0 false0 falseDuplicate keys are not rejected automatically
package main
import ( "encoding/json" "fmt" "strings")
func check(e error) { if e != nil { panic(e) }}
func main() { var p struct { N int `json:"n"` } d := json.NewDecoder(strings.NewReader(`{"n":1,"n":2}`)) d.DisallowUnknownFields() check(d.Decode(&p)) fmt.Println(p.N)}In this scalar example the later duplicate replaces the earlier value. Other values can merge. If the protocol forbids duplicates, add an explicit key-level policy and tests rather than assuming strict decoding handles them.
Expected output:
2Try it locally
Use io.LimitReader with budget 4 plus one byte on "12345"; print whether it exceeds the budget.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Serialization 04: Validate unknown fields and request sizes
Check the lesson objective before moving on.
Why read limit+1 bytes?
What must a second Decode return for exactly one JSON value?