Documentation
¶
Overview ¶
Step 9 of 13: a middleware, and where it runs.
A middleware is an ordinary handler that calls ctx.Next() to run the rest of the chain. Work before Next sees the request, work after Next sees the response. logRequests below times every request and logs the method, path and status.
Where you register it decides what it sees:
app.UseRouter(h) before routing: every request, including 404s and CORS preflights
app.Use(h) after routing, before the matched handler: matched routes only
r.Use(h) the same, scoped to one router and its children (requireShelf in step 7)
r.Post("/", g, h) positional: one route (requireUnlocked in step 7)
The error map from step 4 sits in app.Use, because it only has work to do on matched routes. The logger goes in app.UseRouter, so a typo in a path is logged like everything else. Step 12 shows the same two slots on the builder: RouterMiddlewares(...) and Middlewares(...).
Learn: write a middleware, and pick between UseRouter, Use and a positional guard on purpose. Before: ../08-pagination
Run:
go run main.go
Try:
curl localhost:8080/api/shelves # 200, and a log line with the duration
curl -i localhost:8080/nothing-here # 404, still logged: UseRouter runs before routing
curl -i -X POST localhost:8080/api/shelves -d '{}' # 400, logged with its status
Next: step 10 adds an admin group behind basic authentication (../10-admin-and-basicauth).