HTTP Middleware
What is middleware?
Middleware wraps an http.Handler to add cross-cutting behaviour โ logging, authentication, rate-limiting, CORS โ without polluting route handlers.
The signature every Go middleware follows:
http.HandlerFunc is a function type that implements http.Handler โ it lets you turn any compatible function into a handler.
Logging middleware
Auth middleware
Short-circuiting (returning before calling next.ServeHTTP) is how middleware rejects requests.
Chaining middleware
Apply multiple middlewares by nesting them:
Or write a Chain helper:
Middlewares are applied right-to-left so that the leftmost runs first on incoming requests.
Capturing the response status
To log the status code, wrap ResponseWriter in a recorder:
Then in the middleware:
Passing values through context
Middleware can attach request-scoped values for downstream handlers:
http.StripPrefix and http.TimeoutHandler
Standard library provides ready-made middleware:
Knowledge Check
What is the standard Go middleware signature?
How does middleware short-circuit a request (prevent the next handler from running)?
Why is http.HandlerFunc useful in middleware?