ip

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 8, 2025 License: MIT Imports: 6 Imported by: 0

README

IP Extractor Library

A Go package for extracting client IP addresses from HTTP requests, handling proxy headers, and managing trusted networks.

Features

  • Supports all standard proxy headers (X-Forwarded-For, Forwarded, CF-Connecting-IP, etc.)
  • RFC7239 Forwarded header parsing
  • Trusted proxy CIDR validation
  • Middleware for seamless integration with net/http
  • IPv4/IPv6 support
  • Customizable header priority

Notes

  • Invalid IPs in headers are automatically skipped
  • IPv6 addresses are returned without zone identifiers
  • By default trusts all proxies (configure properly for production)

Documentation

Overview

Package ip provides tools for extracting client IP addresses from HTTP requests, handling proxy headers, and managing trusted networks.

Index

Constants

View Source
const (
	XForwardedFor    = "X-Forwarded-For"     // Load-balancers (AWS ELB) or proxies.
	Forwarded        = "Forwarded"           // RFC7239.
	XRealIP          = "X-Real-IP"           // Default nginx proxy/fcgi; alternative to x-forwarded-for, used by some proxies.
	XClientIP        = "X-Client-IP"         // Standard headers used by Amazon EC2, Heroku, and others.
	CfConnectingIP   = "CF-Connecting-IP"    // @see https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers-.
	FastlyClientIP   = "Fastly-Client-IP"    // Fastly and Firebase hosting header (When forwared to cloud function).
	TrueClientIP     = "True-Client-IP"      // Akamai and Cloudflare: True-Client-IP.
	XClusterClientIP = "X-Cluster-Client-IP" // Rackspace LB and Riverbed's Stingray.
	XForwarded       = "X-Forwarded"
	ForwardedFor     = "Forwarded-For"
)

Header constants represent common HTTP headers used for client IP detection.

Variables

This section is empty.

Functions

func Ctx

func Ctx(ctx context.Context) (netip.Addr, bool)

Ctx retrieves the IP address from the request context.

func ExtractFor

func ExtractFor(s string) string

ExtractFor parses a single Forwarded header value string and returns the value of the first "for=" parameter. Handles optional quotes and IPv6 brackets, e.g. `for="[2001:db8::1]:443"` or `for=192.0.2.43`. If the "for" parameter is not found, an empty string is returned.

func FieldsSeqXForwardedFor

func FieldsSeqXForwardedFor(s string) iter.Seq[string]

FieldsSeqXForwardedFor splits a string of IPs from an X-Forwarded-For header into a sequence of fields. It ignores spaces and commas between IPs, yielding each value to the caller function.

func ParseAddr

func ParseAddr(addr string) (netip.Addr, error)

ParseAddr parses s as an IP address, returning the result. The string s can be in dotted decimal ("192.0.2.1"), IPv6 ("2001:db8::68"), or IPv6 with a scoped addressing zone ("fe80::1cc0:3e8c:119f:c2e1%eth0").

func ParseAddrPort

func ParseAddrPort(addrPort string) (netip.Addr, error)

ParseAddrPort parses s as an netip.AddrPort.

It doesn't do any name resolution: both the address and the port must be numeric.

func ParseForwarded

func ParseForwarded(addrs []string) (netip.Addr, bool)

ParseForwarded parses the "Forwarded" HTTP headers and extracts the first valid IP address from the "for=" parameter. Returns the extracted IP and true if parsing succeeds, or zero IP and false otherwise.

func ParseXForwardedFor

func ParseXForwardedFor(header string) (netip.Addr, bool)

ParseXForwardedFor parses an X-Forwarded-For header value and returns the first valid IP address. Sometimes IP addresses in this header can be 'unknown' (http://stackoverflow.com/a/11285650). A Squid configuration directive can also set the value to "unknown" (http://www.squid-cache.org/Doc/config/forwarded_for/). Therefore taking the left-most IP address that is not unknown.

func WithContext

func WithContext(ctx context.Context, v netip.Addr) context.Context

WithContext adds an IP address to the context.

Types

type Extractor

type Extractor struct {
	// contains filtered or unexported fields
}

Extractor configures IP extraction rules and trusted proxies. Use New() to create instances with optional configuration.

func New

func New(opts ...Option) *Extractor

New creates a new Extractor with optional configuration options. By default, it includes commonly used HTTP headers for identifying the client IP. Use WithHeaders and WithTrustedProxies to customize behavior.

func (*Extractor) FromRequest

func (e *Extractor) FromRequest(r *http.Request) (netip.Addr, bool)

FromRequest extracts the client's IP address from the given HTTP request. It uses the configured headers in priority order and checks whether the remote address is a trusted proxy. If so, it attempts to retrieve the original client IP from headers. Returns (IP, true) on success, or (zero value, false) if extraction fails.

func (*Extractor) Middleware

func (e *Extractor) Middleware(next http.Handler) http.Handler

Middleware returns an HTTP middleware that injects the client's IP address into the request context, using the Extractor's logic.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option sets options such as parameters.

func WithHeaders

func WithHeaders(headers ...string) Option

WithHeaders overrides default header list.

func WithTrustedProxies

func WithTrustedProxies(proxies ...string) Option

WithTrustedProxies sets list of trusted proxies (CIDR or IP format).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL