Skip to Content

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

FieldTypeDefaultDescription
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:

  1. CF-Connecting-IP - Cloudflare
  2. X-Real-IP - Nginx proxy
  3. X-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

  1. Header Inspection: Checks headers in the order they appear in the configuration
  2. First Match: Uses the first non-empty header value as the client IP
  3. RemoteAddr Update: Sets r.RemoteAddr to the discovered IP
  4. 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