HTTP layer and tests
HTTP layer and tests
The HTTP layer translates network input into domain operations. Keep handlers small so most behaviour can be tested without HTTP.
What you will learn
- cap and strictly decode JSON requests;
- produce a consistent JSON error shape;
- test handlers with
httptest; - test persistence with
t.TempDir; - shut down without abandoning active requests.
Decode one bounded value
func decodeJSON(w http.ResponseWriter, r *http.Request, destination any) error {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MiB policy
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(destination); err != nil {
return fmt.Errorf("decode body: %w", err)
}
if err := decoder.Decode(&struct{}{}); err != io.EOF {
return errors.New("body must contain one JSON value")
}
return nil
}
The limit is a policy choice. Rejecting unknown fields catches mistakes but is also a compatibility decision that must be documented.
Do not return filesystem paths, stack traces, or raw internal errors. Log safe details on the server and send a stable public message.
Test each boundary
Use httptest.NewRequest and httptest.NewRecorder for handler tests. Cover malformed JSON, unknown fields, blank titles, oversized bodies, missing notes, wrong methods, and success. Assert decoded values, status, and content type—not encoder whitespace.
For persistence, create a path under t.TempDir, write through one store, construct another from the same path, and verify reload. Test invalid JSON without touching user data.
Use http.Server.Shutdown with a deadline-bound context on SIGINT or SIGTERM. Stop new work and let active handlers finish within the deadline.
Practice
Name one domain, store, handler, and full-server test. What does each uniquely catch?
- Domain tests catch validation rules.
- Store tests catch encoding, replacement, and reload.
- Handler tests catch routing, status mapping, headers, and decoding.
httptest.Servertests catch real client/server integration and paths.
Keep most cases in the cheapest layer and only a few wiring tests.
Summary
- Bound requests and define JSON compatibility policy.
- Keep public errors stable and internal detail private.
- Test each boundary with the smallest suitable tool.
- Add graceful shutdown before deployment.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.