Skip to content

Table of Contents

Month 4 · Week 1 — Exercises

Practice for the Week 1 themes (net/http, routing, middleware, JSON). Each folder is its own package with a solution .go file and a table-driven *_test.go driven by net/http/httptest. Standard library only.

Exercise Concept Day Run tests
respond/ JSON/Error response helpers, Content-Type, status, no HTML escaping 089 go test ./respond
middleware/ Chain combinator (outermost-first) + panic Recoverer -> 500 088 go test ./middleware
pathrouter/ Go 1.22 ServeMux method routing + {id} PathValue, auto 404/405 085/087 go test ./pathrouter

How to use

  1. Try it yourself first — move the solution .go aside and re-implement from the prompt.
  2. Run go test ./... from this directory.
  3. Compare with the provided solution; log differences in your day note's "Mistakes" section.

Prompts

  • respond: implement JSON(w http.ResponseWriter, status int, v any) error that sets Content-Type: application/json; charset=utf-8 before WriteHeader, encodes v with SetEscapeHTML(false), and returns the encoder error. Add Error(w, status, msg) that emits {"error": msg}. Verify with httptest.NewRecorder: status, header, and exact body (the Encoder appends a trailing \n).
  • middleware: implement type Middleware func(http.Handler) http.Handler, a Chain(mws ...Middleware) Middleware where mws[0] is the outermost layer (Chain(A,B)(h) == A(B(h))), and a Recoverer that turns a downstream panic into a 500 without crashing the server. Prove order with a recording middleware and prove recovery flips a panicking handler to 500.
  • pathrouter: build NewMux(*Store) *http.ServeMux with GET /notes and GET /notes/{id}, reading the wildcard via r.PathValue("id"). Let the mux produce 404 for unknown paths and 405 (with an Allow header) for the wrong method — don't hand-write those.

Results table

Exercise Tests -race clean Notes
respond exact-body assertions catch the trailing newline + HTML-escape default
middleware recording middleware confirms outermost-first composition
pathrouter Store guarded by RWMutex; run go test -race ./pathrouter