How Middleware Works
Middleware wraps handlers to add functionality:Middleware Execution Order
Global Middleware
Apply to all routes viaapp.Use():
File-Based Middleware
Createmiddleware.go in any app directory:
app/middleware.go- Applies to all routesapp/api/middleware.go- Applies to/api/*app/api/protected/middleware.go- Applies to/api/protected/*
app/api/middleware.go:
Built-in Middleware
Request Logger (App-Level)
Fuego includes an app-level request logger that captures all requests, including those handled by the proxy layer. The logger is enabled by default.Configuration
Log Levels
| Level | What’s Logged |
|---|---|
LogLevelDebug | Everything + internal details |
LogLevelInfo | All requests (default) |
LogLevelWarn | 4xx + 5xx only |
LogLevelError | 5xx only |
LogLevelOff | Nothing |
Environment Variables
FUEGO_LOG_LEVEL- Set log level (debug,info,warn,error,off)FUEGO_DEV=true- Automatically sets debug levelGO_ENV=production- Automatically sets warn level
Disable/Enable Logger
Recover
Recovers from panics and returns 500 error:RequestID
Adds a unique request ID header:X-Request-Id: abc123...
CORS
Handle Cross-Origin Resource Sharing:Timeout
Set request timeout:BasicAuth
Simple username/password authentication:SecureHeaders
Add security-related headers:X-Content-Type-Options: nosniffX-Frame-Options: SAMEORIGINX-XSS-Protection: 1; mode=blockReferrer-Policy: strict-origin-when-cross-origin
RateLimiter
Limit requests per IP:Custom Middleware
Create your own middleware using the factory pattern:Authentication Middleware Example
Here’s a complete authentication middleware:Middleware vs Proxy
| Feature | Middleware | Proxy |
|---|---|---|
| Runs | After routing | Before routing |
| URL rewriting | No | Yes |
| Access route params | Yes | No |
| Per-route control | Yes | Via matchers |
| Location | middleware.go | app/proxy.go |
Best Practices
Order matters
Order matters
Add recover first, then other middleware. The order you add middleware determines execution order.
Keep it focused
Keep it focused
Each middleware should do one thing well. Don’t combine authentication, logging, and timing in one middleware.
Handle errors properly
Handle errors properly
Return proper errors, don’t panic. Use the error helpers like
fuego.Unauthorized().Use context for sharing data
Use context for sharing data
Store shared data with
c.Set() and retrieve with c.Get().Be careful with state
Be careful with state
Middleware runs concurrently. Avoid shared mutable state without proper synchronization.