Lesson 2 of 9 · 24m
Routing, Validation, and Errors That Help Instead of Leak
Make request contracts explicit, validate at the boundary, and shape errors so clients get useful answers without internal details escaping.
Most incidents I have reviewed did not begin as sophisticated attacks. They began as ambiguous input meeting optimistic code. The service accepted whatever arrived, interpreted it generously, and failed somewhere far from the boundary. In Go the fix is not a giant framework. It is a contract: decode deliberately, validate immediately, and return errors clients can rely on.
Decode with limits
json.Decoder gives you control when you bother to use it:
func decodeJSON(w http.ResponseWriter, r *http.Request, dst any) error {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MiB
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return fmt.Errorf("invalid JSON: %w", err)
}
if dec.More() {
return errors.New("body must contain one JSON document")
}
return nil
}Size limits, strict fields, and one-document decoding prevent large operational surprises. A service accepting unbounded bodies is volunteering to be memory-shaped by strangers.
Validate semantics, not only syntax
Valid JSON is not necessarily a valid request:
func (r CreateOrderRequest) Validate() error {
if r.CustomerID == "" {
return errors.New("customer_id is required")
}
if len(r.SKU) > 64 || !skuPattern.MatchString(r.SKU) {
return errors.New("sku is invalid")
}
if r.Quantity < 1 || r.Quantity > 100 {
return errors.New("quantity must be between 1 and 100")
}
return nil
}Boundary validation protects input shape; domain invariants still protect business truth. Those are separate jobs.
Error responses are an API contract
A useful error tells the client what happened, whether retrying might help, and gives a stable machine-readable code:
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
Retry bool `json:"retryable"`
}Do not make clients parse prose, and do not leak stack traces, SQL, file paths, or internal hostnames.
Map internal errors deliberately
Not every storage error is a 500:
switch {
case errors.Is(err, ErrNotFound):
writeError(w, 404, "order_not_found", "order not found", false)
case errors.Is(err, ErrConflict):
writeError(w, 409, "order_conflict", "order already exists", false)
case errors.Is(err, context.DeadlineExceeded):
writeError(w, 504, "upstream_timeout", "dependency timed out", true)
default:
writeError(w, 500, "internal_error", "internal error", true)
}Log the internal cause once, with context. Return the external meaning. Those are different audiences with different needs.
Field notes
DisallowUnknownFieldscatches typos but can break forward-compatible clients; choose deliberately.- Never echo raw validation input into logs when it may contain tokens or personal data.
- A 400 should tell the caller what to fix; a 500 should not describe your storage layout.
- Decode and validate before
WriteHeaderwhenever possible; partial responses are operationally ugly.
Was this lesson helpful?