DevPath
Mid lesson · 12 min

Decode JSON strictly and test the contract

Reject unknown fields and distinguish malformed input from domain errors.

Set a clear input policy

A decoder normally maps known JSON fields and may ignore unknown ones. For a narrow API, DisallowUnknownFields can catch misspellings rather than silently accepting them. Also limit request size and reject trailing JSON values when the endpoint expects one object. Validate domain rules after decoding.

Decode one value

Return a client error for malformed JSON and a field-level validation response for a well-formed but invalid object. Do not expose decoder internals or stack traces. Keep optional fields distinct from omitted ones when that distinction changes behavior.

dec := json.NewDecoder(io.LimitReader(r.Body, maxBytes))
dec.DisallowUnknownFields()
if err := dec.Decode(&input); err != nil { /* respond 400 */ }

Table-drive edge cases

Use named cases for valid input, unknown field, wrong type, empty body, and trailing object. Include the expected status and whether any write should occur. Names make failures readable and let a new contributor add a regression case without duplicating the whole setup.

Check your understanding

Does DisallowUnknownFields also validate a field's business range?

Show explanation

No. It rejects unexpected keys; range and cross-field rules still need explicit validation.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Depend on an interface, not a struct

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.