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
Built-in middleware
Mizu includes one middleware by default:Writing middleware
Basic 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:Conditional middleware
Apply middleware based on request: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() |