What is middleware?
Middleware sits between the incoming request and your handler. It can:- Run code before the handler (check auth, log start time)
- Run code after the handler (log duration, add headers)
- Short-circuit the request (reject unauthorized users)
- Modify the request or response
The middleware signature
A middleware is a function that takes a handler and returns a new handler:Applying middleware
Global middleware
Apply to all routes withapp.Use():
Scoped middleware
Apply to specific routes withapp.With():
Group middleware
Apply to a group of routes:Execution order
Middleware runs in the order you add them. For the chainA β B β C β handler:
Abefore βBbefore βCbefore βhandlerhandlerreturnsCafter βBafter βAafter
Writing middleware
Authentication middleware
CORS middleware
Recovery middleware
Middleware with configuration
Use the options pattern for configurable middleware:Passing data between middleware
Use Goβs context to pass data from middleware to handlers:Using net/http middleware
Mizu can use standardnet/http middleware via Compat.Use():
Common patterns
Skip paths
Donβt run middleware on certain paths:Summary
| Concept | Description |
|---|---|
| Signature | func(Handler) Handler |
| Global | app.Use(middleware) |
| Scoped | app.With(middleware) |
| Group | Inside app.Group() callback |
| Order | First added runs first |
| net/http compat | app.Compat.Use() |