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
Middleware keeps your handlers focused on business logic while handling cross-cutting concerns in reusable, composable functions.