Middleware
Middleware should wrap request handling for cross-cutting concerns without obscuring request ownership, error flow, or cancellation.
Canonical guidance
- keep middleware focused
- preserve request context and ownership
- make chain order intentional
Use when
- logging
- panic recovery
- authentication gates
- request metrics or tracing
Avoid
- burying domain logic in wrappers
- middleware that starts detached goroutines
- wrapper stacks so deep that request flow becomes opaque
Preferred pattern
- compose a small chain of focused wrappers around the final handler
Anti-pattern
- one “middleware” that parses config, talks to databases, mutates globals, and serves requests
Explanation: This is tempting because wrappers are easy to stack, but broad middleware becomes hidden application logic.
Why
- middleware is useful only while request flow stays legible
Related pages
Sources
- net/http package - Go Team