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¶
- Try it yourself first — move the solution
.goaside and re-implement from the prompt. - Run
go test ./...from this directory. - 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) errorthat setsContent-Type: application/json; charset=utf-8beforeWriteHeader, encodesvwithSetEscapeHTML(false), and returns the encoder error. AddError(w, status, msg)that emits{"error": msg}. Verify withhttptest.NewRecorder: status, header, and exact body (theEncoderappends a trailing\n). - middleware: implement
type Middleware func(http.Handler) http.Handler, aChain(mws ...Middleware) Middlewarewheremws[0]is the outermost layer (Chain(A,B)(h) == A(B(h))), and aRecovererthat 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.ServeMuxwithGET /notesandGET /notes/{id}, reading the wildcard viar.PathValue("id"). Let the mux produce 404 for unknown paths and 405 (with anAllowheader) 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 |