Middleware
Middleware provides a way to execute code before and after HTTP requests.
Overview
Middleware functions follow the standard Go HTTP middleware pattern:
func(next http.Handler) http.HandlerThey can be chained together and applied globally to all routes or to specific route groups.
Registering Middleware
Every middleware in this guide can be added at three levels: the mux, a group, or a single route.
server.Use(mrecover.Middleware()) // mux: every route registered after this call
api := server.Group("/api", mrequestid.Middleware()) // group: routes under /api
api.GET("/users", handler, timeout.Middleware(5*time.Second)) // single routeCross-cutting middlewares such as Recover, Request ID, Log, and CORS usually sit at the top of the chain on the mux.
Bundled Middleware
| Middleware | Package | Purpose |
|---|---|---|
| Recover | middleware/recover | Recover from panics and answer with a safe 500 |
| Request ID | middleware/requestid | Assign an X-Request-Id to every request |
| Log | middleware/log | Log requests and responses with slog |
| Rate Limit | middleware/ratelimit | Limit traffic globally, per IP, or per key |
| Body Limit | middleware/bodylimit | Cap request body size |
| Timeout | middleware/timeout | Attach a deadline to the request context |
| CORS | middleware/cors | Handle cross-origin requests |
| Telemetry | middleware/telemetry | OpenTelemetry traces and metrics |
| Encoding | middleware/encoding | Gzip response compression |
| Server | middleware/server | Set the Server response header |
| ForwardAuth | middleware/forwardauth | Delegate authentication to an external service |
| Auth | middleware/auth | Sessions, login strategies, MFA, and a login UI |
Middleware Order
The order of middleware matters. Middleware is executed in the order they are added:
- Global middleware (added via
mux.Use()) is executed first - Group middleware is executed next
- Route-specific middleware is executed last
- Your handler is executed at the end
mux.Use(middleware1, middleware2) // Global: 1, 2
api := mux.Group("/api", middleware3) // Group: 1, 2, 3
api.GET("/users", handler, middleware4) // Route: 1, 2, 3, 4, handlerINFO
Middleware added with Use only affects handlers and groups registered after the call; it does not apply to routes or groups defined earlier.
Runtime Reload
Ada supports replacing, disabling, and adding middlewares at runtime without restarting the server. See the Runtime Reload guide for details on Slot and Pipeline.
// Single toggleable middleware
auth := ada.NewSlot(forwardauth.Middleware(...))
server.Use(auth.Middleware())
// Replace at runtime
auth.Replace(forwardauth.Middleware(newOpts...))
auth.Disable()
auth.Enable()Creating Custom Middleware
You can create your own middleware functions following the standard pattern:
func authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check authentication
token := r.Header.Get("Authorization")
if token == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Validate token (implement your logic here)
if !isValidToken(token) {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
// Call the next handler
next.ServeHTTP(w, r)
})
}
func rateLimitMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Implement rate limiting logic
if isRateLimited(r) {
http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}