Real IP Middleware
The Real IP middleware extracts the real client IP address from proxy headers and sets it as r.RemoteAddr
. This is essential when your application runs behind load balancers, CDNs, or reverse proxies that add IP information to request headers.
Features
- Automatic IP Detection: Checks common proxy headers by default
- Configurable Headers: Add custom headers to check
- First Match Wins: Uses the first non-empty header value found
- Proxy-Friendly: Works with Cloudflare, AWS ALB, Nginx, and other proxies
Basic Usage
middleware.go
httpx.Chain(
middlewares.RealIP(nil), // Uses default headers
)
Configuration
Configure custom headers using IPOptions
:
middleware.go
httpx.Chain(
middlewares.RealIP(&middlewares.IPOptions{
Headers: []string{"X-Custom-IP", "X-Client-IP"},
}),
)
IPOptions Fields
Field | Type | Default | Description |
---|---|---|---|
Headers | []string | ["CF-Connecting-IP", "X-Real-IP", "X-Forwarded-For"] | Additional headers to check for client IP |
Default Headers Checked
The middleware checks these headers in order:
CF-Connecting-IP
- CloudflareX-Real-IP
- Nginx proxyX-Forwarded-For
- Standard proxy header
Common Configurations
With AWS Load Balancer
middlewares.RealIP(&middlewares.IPOptions{
Headers: []string{"X-Forwarded-For"},
})
With Custom Proxy
middlewares.RealIP(&middlewares.IPOptions{
Headers: []string{"X-Client-IP", "X-Real-IP"},
})
Multiple Proxy Layers
middlewares.RealIP(&middlewares.IPOptions{
Headers: []string{
"CF-Connecting-IP", // Cloudflare
"X-Forwarded-For", // Load balancer
"X-Real-IP", // Nginx
"X-Client-IP", // Custom
},
})
How It Works
- Header Inspection: Checks headers in the order they appear in the configuration
- First Match: Uses the first non-empty header value as the client IP
- RemoteAddr Update: Sets
r.RemoteAddr
to the discovered IP - Fallback: If no headers contain IP,
r.RemoteAddr
remains unchanged
Enabled by Default
The IP middleware is enabled by default in the HTTP server configuration at (internal/provide/provide_http.go
):
Important Notes
- Header Order: The middleware checks headers in the order specified
- Custom Headers: Additional headers are appended to the default list
Last updated on