Skip to main content

Overview

The realip middleware extracts the real client IP address from proxy headers. It’s essential when running behind load balancers or reverse proxies.

Installation

Quick Start

Configuration

Default Headers (checked in order)

  1. X-Forwarded-For
  2. X-Real-IP
  3. CF-Connecting-IP (Cloudflare)
  4. True-Client-IP

Examples

Basic Usage

Trusted Proxies

Custom Configuration

API Reference

Technical Details

IP Extraction Process

The middleware follows a systematic approach to extract the real client IP:
  1. Remote IP Extraction: Extracts the IP from Request.RemoteAddr using net.SplitHostPort
  2. Proxy Trust Verification: Checks if the remote IP is in the trusted proxy list (CIDR notation supported)
  3. Header Processing: If trusted, iterates through configured headers in priority order
  4. IP Parsing: Extracts the first valid IP from comma-separated header values (for X-Forwarded-For)
  5. Fallback: Uses RemoteAddr if no valid IP found in headers

CIDR Network Parsing

The middleware automatically converts single IP addresses to CIDR notation:
  • IPv4 addresses: /32 suffix (e.g., 10.0.0.1 becomes 10.0.0.1/32)
  • IPv6 addresses: /128 suffix (e.g., ::1 becomes ::1/128)

Context Storage

The real IP is stored in the request context using a private contextKey{} type, preventing key collisions with other middleware or application code.

Header Priority

When multiple headers are set, the middleware checks them in the configured order and uses the first valid IP found. Default priority:
  1. X-Forwarded-For (supports comma-separated lists)
  2. X-Real-IP
  3. CF-Connecting-IP (Cloudflare)
  4. True-Client-IP

Security

Only trust proxy headers when behind a trusted proxy. Without TrustedProxies, all requests are trusted.

Testing

The middleware includes comprehensive test coverage for various scenarios: