Go · Chapter 22 of 26
Middleware
By the end of this chapter you can write middleware, a function that takes an http.Handler and returns one, log every request with log/slog, see the status a handler wrote, turn a panic into a 500 with recover, refuse a request before it reaches the app, carry a request id in the context, give a handler a time limit, and put a chain of middleware in the right order. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Services
- 4 tasks
- Go
- In the all labs plan
The first 2 chapters of Go are free. This one comes with the all labs plan.
Why you need this
Chapter 21's charger API is live: partner apps ask for a charger's status and chargers post heartbeats. On its first evening Tenzin had three problems. He could not say which requests had been slow or had failed, because the API logged nothing. One request for a charger with a missing record crashed its handler, and the partner app got no answer at all, not even an error. And anyone who found the address could call the API, while Nandini had promised partners that only apps with a key would get in.
You could add a log line, a crash guard and a key check to every handler. With three handlers that is nine copies of the same code, and the fourth handler someone writes next month will forget one of them. These jobs are about every request, not about chargers, so they belong in one place that wraps the whole API: middleware.
What you build: 4 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
logging.go: a log line for every request
Tenzin wants one log line for every request, written after the request is served. In logging.go, write Logging(logger *slog.Logger, next http.Handler) http.Handler. The handler it returns calls next, then logs with logger at level Info, with the message "request" and these attributes:
method: the request's method, like GET
path: the URL's path, like /chargers/C1042
status: the status the client got, as an int
duration: how long next took, as a time.Duration
The response must reach the client unchanged (status, headers and body). The Check logs with slog's JSON handler and serves GET /chargers/C9999 with a handler that takes 20ms and answers 404 (the line must say status 404 and a duration of at least 20ms), then POST /heartbeats with a handler that writes a body and never calls WriteHeader (status 200). Exactly one line for each request.
- Task 2
recover.go: a panic becomes a 500
In recover.go, write Recover(logger *slog.Logger, next http.Handler) http.Handler. The handler it returns calls next. If next panics, it catches the panic, logs with logger at level Error with the message "panic" and the attributes path (the URL's path) and error (the panic's value as text: panic("boom") logs boom), and answers with http.Error, the text "internal server error" and status 500.
The Check serves GET /crash with a handler that calls panic("boom"): no panic may get out, the status must be 500, the body "internal server error" with http.Error's line break, and there must be exactly one log line. A handler that does not panic (it answers 202 "queued") passes through unchanged and logs nothing.
- Task 3
apikey.go: no key, no entry
In apikey.go, write RequireKey(key string, next http.Handler) http.Handler. The handler it returns calls next only when the request's header X-API-Key is exactly key. Otherwise it answers with http.Error, the text "missing or wrong API key" and status 401 (Unauthorized), and next does not run at all.
Comparing with crypto/subtle's ConstantTimeCompare is the careful way, so a key cannot be guessed by timing; a plain comparison passes too. The Check uses the key k-7Qx and tries no header, the key k-7Qy, the key k-7Qx-extra (all refused with 401 and that body, next not called) and the key k-7Qx (next answers, once).
- Task 4 · interview question
Interview: chain.go, the order of the chain
Tenzin put your three middlewares around the app in NewAPI(logger *slog.Logger, apiKey string, app http.Handler) http.Handler. Requests work, but his log has no request line for requests refused with 401, and none for the request that panicked. Fix the order so that every request gets a "request" line with the status the client really got:
no key: 401, the app does not run, and a request line with status 401
a route that panics, with the key: 500, a request line with status 500, and Recover's "panic" line
the right key: the app's 200 and its request line
The Check uses your Logging, Recover and RequireKey, so Tasks 1 to 3 must pass first.
Joseph will ask: in which order do logging, auth and recovery go, and why does the order matter at all?
What you will learn
- func(http.Handler) http.Handler: the shape of every middleware, a handler around a handler.
- log/slog: Go's structured logger, with levels and named attributes, writing text or JSON to any io.Writer.
- Wrapping the ResponseWriter: a type of your own that sees what the handler writes.
- recover: catching a panic in a deferred function.
- Stopping early: answering without calling the next handler.
- The order of the chain: the outside runs first and finishes last.
- context.WithValue and http.TimeoutHandler: a request id that travels with the request, and a time limit for a slow handler.
More in Services
Build "Middleware" yourself
BijliGo, a Bengaluru EV charging network, drops chargers at the evening peak. You rewrite its backend in Go. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Go are free. This one comes with the all labs plan.