lightweight, idiomatic Go HTTP router
Find a file
Vojtech Vitek (golang.cz) 3b171578ca
feat: middleware.ClientIP, a replacement for middleware.RealIP (#967)
* ClientIP middleware proposal, intended to replace RealIP

* ClientIP middleware: address PR feedback and security advisories

Rework the new ClientIP* middlewares per reviewer feedback (c2h5oh,
adam-p, rezmoss, Saku0512) and align with the documented attack
patterns in GHSA-3fxj-6jh8-hvhx, GHSA-rjr7-jggh-pgcp, GHSA-9g5q-2w5x-hmxf.

API:
- Rename ClientIPFromXFFHeader -> ClientIPFromXFF.
- Add ClientIPFromXFFTrustedProxies(n) for dynamic proxy pools where
  enumerating CIDRs isn't practical (autoscaling, ephemeral containers).
- Add GetClientIPAddr alongside GetClientIP; both back to a single
  netip.Addr stored in context. r.RemoteAddr is never mutated.
- Drop IsLoopback/IsPrivate filtering: the user's explicit trust
  configuration is authoritative (k8s nginx-ingress and similar
  legitimately surface those values).
- Merge multiple X-Forwarded-For header instances before walking
  (RFC 2616), defeating duplicate-header attacks.
- Deprecate middleware.RealIP with citations to all three advisories
  and guidance pointing at the new API.

Docs:
- Per-function godoc explains exactly when each variant applies.
- Example_clientIP is a single, consolidated decision guide rendered
  on pkg.go.dev.

Tests: 56 subtests including explicit PoC reproductions of each
advisory, /24 boundary cases (Saku0512), IPv6, multi-header merging,
spoofing prevention, and middleware chaining (rezmoss).

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-Authored-By: Claude Sonnet 4.7 <noreply@anthropic.com>

* Drop first-write-wins semantics, we want users to use exactly one middleware

* ClientIPFromXFFTrustedProxies: drop fallback-chaining hint from godoc

Saku0512 correctly flagged in #967 that the godoc told users to register
ClientIPFromRemoteAddr *after* ClientIPFromXFFTrustedProxies for fallback
behavior. With last-write-wins semantics (482e855) that recipe is actively
wrong: on the happy path RemoteAddr would silently overwrite the legitimate
XFF-derived client IP with the immediate proxy's address — reintroducing the
spoofing-prone behavior this API was written to prevent.

Rather than just reverse the order in the example, drop the chaining hint
entirely. The whole point of 482e855 was to push users toward picking exactly
one ClientIPFrom* middleware; documenting a chaining recipe in one specific
function works against that. The honest statement is "no client IP is set
and GetClientIP returns \"\"" — what the caller does about it is on them.

Also rename TestClientIPChaining -> TestClientIPLastWriteWins and reword its
subtests to describe the property being locked down rather than endorsing a
fallback recipe. Same coverage, no implicit recommendation.

* ClientIP: add failing regression tests for v4-mapped / zoned IP bypasses

Per PR #967 review, demonstrate three concrete gaps that the
rightmost-untrusted XFF algorithm and ClientIPFromRemoteAddr don't catch:

1. v4-mapped IPv6 in XFF escapes a v4 trusted prefix
   (netip.Prefix.Contains is false for ::ffff:a.b.c.d vs a.b.c.0/N).
   Internal-address spoof and loopback spoof variants.

2. Zoned IPv6 in XFF escapes a v6 trusted prefix
   (netip.Prefix.Contains is false for any zoned address).

3. v4-mapped IPv6 RemoteAddr is returned in its v6 form, splitting one
   logical client across two rate-limit buckets / log keys / prefix
   checks depending on dual-stack listener configuration.

These tests are EXPECTED TO FAIL on this commit; the follow-up commit
will land the fixes (Unmap() + zone-strip at parse time).

The previously discussed "empties don't shift TrustedProxies slot"
property is not a bypass — current behavior is already correct — so
it will be added as a regression-pin test alongside the fixes rather
than committed here as failing.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ClientIP: normalize v4-mapped IPv6 and strip header zones; README migration

Fixes three gaps surfaced by the PR #967 review (failing tests added in the
previous commit now pass):

1. v4-mapped IPv6 in XFF escaping a v4 trusted prefix. netip.Prefix.Contains
   returns false for ::ffff:a.b.c.d checked against a.b.c.0/N, so an attacker
   able to inject the v4-mapped form of an internal address could escape the
   trust list. Fix: a single parseHeaderAddr helper Unmap()s before the
   prefix check and before storage. Applied uniformly in
   ClientIPFromHeader, the rightmost-untrusted XFF walk, and the
   ClientIPFromXFFTrustedProxies slot lookup.

2. Zoned IPv6 in XFF escaping a v6 trusted prefix. netip.Prefix.Contains
   returns false for any zoned IP, and zone identifiers carry no meaning
   across the network, so an attacker-injected zone suffix bypassed the
   trust check. Fix: parseHeaderAddr strips zones via WithZone("") at
   parse time; zones are by definition not valid in header-sourced IPs.

3. ClientIPFromRemoteAddr returning ::ffff:a.b.c.d for v4 clients on
   dual-stack listeners, splitting one logical client into two
   rate-limit / log / ACL keys. Fix: Unmap() before storing. Zone is
   preserved here because RemoteAddr can legitimately be link-local.

Also:
- Pre-canonicalize the user-supplied header name in ClientIPFromHeader
  at construction time, matching the realip.go pattern and saving a
  per-request canonicalization on the hot path. A package-level
  xForwardedForHeader constant documents the canonical XFF spelling.
- Per-function godoc explicitly notes the v4-mapped folding and zone
  stripping so downstream callers understand the normalization contract.
- New regression-pin tests: empties don't shift the
  ClientIPFromXFFTrustedProxies slot index; positive normalization tests
  for v4-mapped and zoned inputs in each entry point.
- README: deprecate the RealIP row, add ClientIPFrom* entries, and
  introduce a "Choosing a ClientIP middleware" section with copy-paste
  recipes for the common deployments (direct internet, Cloudflare,
  CloudFront, dynamic-IP proxy pools).

Co-authored-by: Cursor <cursoragent@cursor.com>

* Improve comments and README

* Update middleware.Logger to work with ClientIP

* ClientIPFromXFF: zero-allocation lazy right-to-left walk

middleware.ClientIPFromXFF sits in the request hot path of any chi server
running behind a proxy fleet. Per the #967 review, "each allocation counts" —
at high RPS the per-request mergeXFF allocations are small individually but
show up in GC pressure across many handlers.

The previous implementation built a fully materialized merged XFF slice via
mergeXFF, then walked it right-to-left and returned at the first non-trusted
entry. In the common case — one trusted hop, the rightmost XFF entry IS the
client — we paid to allocate and populate the whole chain only to inspect
the last cell.

Replace it with a lazy walker that iterates headers right-to-left and, within
each header, iterates comma-separated entries right-to-left via
strings.LastIndexByte. Substrings alias the original header storage, no
copies. The walker returns at the first parseable non-trusted entry without
ever materializing a slice.

Per-request allocation impact (XFF present, typical "1 header, 3 IPs,
1 trusted hop"):

  Before:  ~4 small allocations
           - initial mergeXFF backing array
           - strings.Split's []string per header value
           - 2 regrowths of the result slice as it fills
  After:   0 allocations
           - returns on the first iteration; nothing materialized

Worst case (entire chain inside trusted prefixes, walker scans all entries):
still 0 allocations.

Correctness validated three independent ways:

  - Algorithm conformance: every requirement of the PR's rightmost-
    untrusted spec maps line-by-line to the new walker — multi-header
    merge, empty/whitespace drop, parse-failure skip, trust-prefix skip,
    normalization via parseHeaderAddr (Unmap + zone strip).

  - Iteration-order equivalence: walking headers in reverse and each
    header's entries in reverse via LastIndexByte yields exactly the
    same sequence as mergeXFF's flat list walked right-to-left.

  - All existing ClientIPFromXFF tests pass: multi-header merge,
    rightmost-untrusted spoofing scenarios, CIDR boundary membership,
    v4-mapped folding, IPv6 zone stripping, security regression pins.

  - Brute-force equivalence fuzz against the original mergeXFF-based
    walker over 200k random inputs (valid IPs, garbage, v4-mapped,
    zoned, whitespace, leading/trailing/double commas, empty headers):
    zero divergences.

mergeXFF is unchanged and still used by ClientIPFromXFFTrustedProxies, which
genuinely needs the total count for slot indexing.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ClientIPFromXFF: add failing tests for fail-closed on unparseable XFF

PR #967 review issue #6 (adam-p): a netip.ParseAddr failure mid-chain in
the rightmost-untrusted walk currently triggers a silent continue. With
that behaviour, a hostile or buggy hop emitting garbage between the
client and a trusted proxy is indistinguishable from no entry at all,
and the walker happily skips past it to return a more-leftward IP — a
spoofable result.

Pin the desired fail-closed contract with TestXFF_FailClosedOnUnparseable
covering three failing cases:

  1. garbage_rightmost_no_prefixes
     XFF "1.1.1.1, garbage" with no trusted prefixes. Today returns
     1.1.1.1 (skip-and-continue); must return "" (fail-closed).

  2. garbage_between_client_and_trusted_proxy
     XFF "203.0.113.7, garbage, 10.0.0.1", trusted 10.0.0.0/8. Today
     skips the trusted hop and the garbage, returns 203.0.113.7. Must
     return "" — we cannot tell whether the entry to the left of garbage
     is the client or another forged hop.

  3. garbage_past_trusted_chain
     Same shape with multiple trusted hops. Identical contract.

Plus one negative case that MUST keep passing (proves fail-closed does
not over-trigger when the walker returns before reaching garbage):

  4. garbage_in_unreachable_left_header
     Headers ["garbage", "203.0.113.7, 10.0.0.1"], trusted 10.0.0.0/8.
     Walker returns 203.0.113.7 from the right header; garbage in the
     left header is never inspected. Already passes today, must still
     pass after the fix.

Also remove the now-obsolete "unparseable_rightmost_skipped" case from
TestClientIPFromXFF_NoTrustedPrefixes — it asserts the old skip-and-
continue behaviour and no longer fits that table's "rightmost-first"
theme. The "weird_with_empties_then_valid_rightmost" comment is updated
to call out that empty/whitespace entries are trimmed before parsing
and so do not trip fail-closed.

Cases 1-3 are EXPECTED TO FAIL on this commit; the follow-up flips
rightmostUntrustedXFF from silent-skip to fail-closed.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ClientIPFromXFF: fail closed on unparseable XFF entries

PR #967 review issue #6 (adam-p): the rightmost-untrusted walk previously
treated a netip.ParseAddr failure the same as a trusted-prefix match —
silently skip and keep walking left. That is unsafe.

Rightmost-untrusted only works because we trust ourselves to be able to
read every hop to the right of the client. An unparseable hop is
indistinguishable from a hostile or missing one. Walking past it can
let us "find" a client IP that is actually any prepended value an
attacker chose to put further left in the chain — exactly the spoofing
shape this middleware was written to prevent.

Flip the !ok branch in rightmostUntrustedXFF from continue to return
(zero, false). Trusted-prefix still continues, empties/whitespace
still skip via trim, fail-closed only fires on actual parse failures.
ClientIPFromXFFTrustedProxies and ClientIPFromHeader are unaffected:
they are single-value reads and already produce no IP on parse failure
by construction.

Godoc:

  - ClientIPFromXFF gets one concise line stating the fail-closed
    contract (visible to library users).
  - rightmostUntrustedXFF's internal comment is expanded to explain
    the security rationale (visible to chi maintainers).

The four cases pinned in the previous commit's TestXFF_FailClosedOnUnparseable
now pass; full middleware test suite stays green.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ClientIPFromXFFTrustedProxies: zero-allocation lazy nthFromRightXFF walk

After 09ddca9 swapped rightmostUntrustedXFF to a lazy right-to-left walk,
mergeXFF was kept only because ClientIPFromXFFTrustedProxies needs
positional indexing — xff[len-N] — into the merged chain. The slice was
allocated and populated every request, even though only one position in
it was ever read.

The same right-to-left iteration that powers rightmostUntrustedXFF
serves this call site with a different stop condition: count down N
non-empty entries from the right, return the Nth. nthFromRightXFF is
that helper. ClientIPFromXFFTrustedProxies's handler becomes a single
call against it; mergeXFF is deleted.

Both XFF middlewares now share one iteration shape (right-to-left lazy
walk over comma-separated entries across all header values, with
substrings aliasing the original header storage) parameterised by stop
condition: "first non-trusted" for rightmostUntrustedXFF, "Nth from
right" for nthFromRightXFF. One less helper to reason about; both paths
become zero-allocation.

Allocation impact for ClientIPFromXFFTrustedProxies (per request with
XFF present, typical "3 IPs, N=2"):

  Before:  ~4 small allocations
           - initial mergeXFF backing array
           - strings.Split's []string per header value
           - 2 regrowths of the result slice
  After:   0 allocations
           - returns at the Nth non-empty entry from the right;
             nothing materialized

Security properties preserved end-to-end — all 12 subtests of
TestClientIPFromXFFTrustedProxies pass unchanged, including the
trickiest pin (empties_dont_shift_slot) which is exactly the property
"do not count empty entries toward N" that nthFromRightXFF's drop-then-
decrement loop guarantees by construction.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ClientIPFromXFF: unify both XFF walkers behind a single walkXFF primitive

After the prior two commits, both XFF middlewares had near-identical
right-to-left scan loops differing only in stop condition (first
non-trusted entry vs Nth non-empty entry from the right). nthFromRightXFF
and rightmostUntrustedXFF together carried ~30 lines of duplicated loop
boilerplate.

Collapse to one primitive:

  walkXFF(headers []string, visit func(entry string) bool)

iterates the merged X-Forwarded-For chain right-to-left and calls visit
on each trimmed non-empty entry; visit returns true to stop the walk.
Both middleware handlers now share this primitive and supply their own
stop condition as a small inline visitor closure (~7 lines each).

Net: -21 lines in middleware/client_ip.go, one fewer concept to reason
about, single source of truth for the (security-critical) walk order
and the empty-entry drop rule.

Zero-allocation property is preserved -- benchmarked side-by-side against
the previous two-helpers implementation:

  BenchmarkRightmost_TwoHelpers    36 ns/op    0 B/op    0 allocs/op
  BenchmarkRightmost_Callback      37 ns/op    0 B/op    0 allocs/op
  BenchmarkNth_TwoHelpers          11 ns/op    0 B/op    0 allocs/op
  BenchmarkNth_Callback            13 ns/op    0 B/op    0 allocs/op

Go's escape analysis keeps the visitor closures (and their captured
&found / &entry / &n locals) on the stack; only cost is one indirect
call per visited entry (~1-2 ns).

All tests still pass (advisory pins, fail-closed pins, multi-header
merge, normalization, boundary CIDR, last-write-wins, panic
conditions). Stale comments in client_ip_test.go that referenced the
removed helpers by name are updated; test names/comments uniformly use
"position" (matching the godoc) for the algorithmic concept and
"entry" for an individual chain value.

Co-authored-by: Cursor <cursoragent@cursor.com>

* client_ip_test: scrub stale "EXPECTED TO FAIL" notes on regression pins

Four test godocs still said "this test is EXPECTED TO FAIL until X
lands" even though X landed in a follow-up commit on this branch.
Misleading to future readers (Copilot PR review flagged 3 of 4).

The tests themselves are unchanged and still pass; they are now
regression pins for behavior the PR already enforces. Reword the
relevant paragraphs from future-tense ("the expected post-fix
behavior is...") to present-tense ("pinned post-fix behavior:
parseHeaderAddr does X") so the doc matches what the test
actually pins.

Affected tests:
  - TestXFF_V4MappedIPv6BypassesTrustedV4Prefix
  - TestXFF_IPv6ZoneIDBypassesTrustedV6Prefix
  - TestClientIPFromRemoteAddr_V4MappedIsUnmapped
  - TestXFF_FailClosedOnUnparseable

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(review): minor README fix

* ClientIPFromHeader: add failing tests for multi-value header attack

PR #967 Copilot review: ClientIPFromHeader uses r.Header.Get(header) to
read the trusted single-IP header. Get returns only the FIRST value Go
saw on the wire. If the trusted header reaches us with two values (a
client-supplied "spoofed" plus a proxy-added "real"), we surface the
client's value -- exactly the bypass shape this middleware was written
to prevent.

The trusted hop is the one CLOSEST to us in the chain, which is the
LAST value, not the first. Same rightmost-untrusted spirit as
ClientIPFromXFF: values from hops further from us are by definition
less trustworthy than what our nearest hop produced. So the
post-fix contract is:

  - Read r.Header.Values(header) (all instances).
  - Take the last entry.
  - parseHeaderAddr it; if it doesn't parse (garbage, empty), no IP
    is set -- do NOT fall back to earlier values (those came from
    less-trusted hops).

TestClientIPFromHeader_MultiValueLastWins pins five cases:

  1. single_value_unchanged (regression pin)
  2. attacker_then_proxy        -- today returns attacker's value
  3. three_values_last_wins     -- today returns attacker's value
  4. last_unparseable_no_fallback -- today falls back to earlier value
  5. last_empty_no_fallback     -- today falls back to earlier value

Cases 2-5 are EXPECTED TO FAIL on this commit; the follow-up flips
ClientIPFromHeader from Get to Values()[len-1].

Co-authored-by: Cursor <cursoragent@cursor.com>

* ClientIPFromHeader: take last value, not first (defense-in-depth)

PR #967 Copilot review: the previous implementation read the trusted
single-IP header with r.Header.Get(header), which returns only the first
value. If the trusted header reaches us with multiple values -- a
client-supplied "spoofed" entry plus the proxy's real entry, or two
proxy-set entries because of upstream chain quirks -- we surfaced the
attacker-controlled first value.

Switch to r.Header.Values(header) and take the LAST entry. The last value
is the one added by the hop closest to us in the chain, which is by
definition the most trusted (the rightmost-untrusted principle we already
apply to X-Forwarded-For). Fail-closed on garbage at the last position:
we do NOT fall back to earlier values, as those came from less-trusted
hops further from us.

Correctly configured proxies (single value, proxy overwrites instead of
appends) are unaffected -- len(values)==1, so first == last == that value.

The four cases pinned in the previous commit's
TestClientIPFromHeader_MultiValueLastWins now pass:

  - attacker_then_proxy        (last value wins)
  - three_values_last_wins     (last value wins)
  - last_unparseable_no_fallback (fail-closed)
  - last_empty_no_fallback     (fail-closed)

Existing ClientIPFromHeader tests stay green. Godoc updated with one
short paragraph naming the multi-value contract.

Co-authored-by: Cursor <cursoragent@cursor.com>

* client_ip: add walkXFF benchmark as O(M) regression pin

PR #967 Copilot review claimed walkXFF is O(n^2) in the number of XFF
entries because it calls strings.LastIndexByte on progressively shorter
substrings, and suggested a DoS-prone CPU cost on attacker-supplied
large XFF headers.

Benchmark refutes the claim. walkXFF is strictly O(M) in total chain
length M -- linear in the entry count n, near-constant for the
single-trusted-hop case (visitor returns true on the first entry).

BenchmarkWalkXFF (visitor walks every entry, worst case for
ClientIPFromXFF when all entries are inside trusted prefixes):

  n=1        5.6 ns/op
  n=10      57.6 ns/op       (5.8 ns/entry)
  n=100    541.1 ns/op       (5.4 ns/entry)
  n=1000   5228   ns/op      (5.2 ns/entry)
  n=10000  55148  ns/op      (5.5 ns/entry)

BenchmarkWalkXFF_RightmostStop (visitor stops at the first entry, the
common case for ClientIPFromXFF with no trusted prefixes and
ClientIPFromXFFTrustedProxies(1)):

  n=1      5.2 ns/op
  n=10     6.0 ns/op
  n=100    6.1 ns/op
  n=1000   6.1 ns/op
  n=10000  6.1 ns/op  -- truly constant

Why the analysis is O(M): strings.LastIndexByte scans BACKWARD from the
end of its input and stops at the first match. After we slice off the
rightmost entry, the next call only scans up to the next comma -- O(L)
where L is that entry's length. Sum over n iterations is O(n*L) = O(M).
On arm64/amd64 it's also SIMD-optimized in the Go runtime, so a
hand-rolled byte loop would lose, not win.

Benchmark stays in the codebase as a regression pin: any future
refactor that accidentally drops back to O(n^2) gets caught here.
Zero allocations preserved across both shapes.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ClientIPFromXFF: doc fix -- no-args case is fail-closed, not skip-and-continue

PR #967 Copilot review: the godoc said "Calling with no arguments returns
the rightmost parseable XFF IP", implying skip-and-continue past garbage.
That phrasing predates the fail-closed change in 5dd2243; the actual
behavior is now "try the rightmost; if it doesn't parse, no IP is set".
Update the line to match.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ClientIPFromXFF*: skip Header.Values canonicalization on the hot path

PR #967 fresh review: r.Header.Values(key) re-canonicalizes the key
through textproto.CanonicalMIMEHeaderKey on every call. xForwardedForHeader
is already a const in canonical form, so the canonicalization is
redundant work in the request hot path.

Replace r.Header.Values(xForwardedForHeader) with the direct map read
r.Header[xForwardedForHeader] in both XFF middleware handlers. Safe
because:

  - Headers received by net/http are stored under canonical keys.
  - Headers set programmatically via r.Header.Set/Add are also stored
    under canonical keys.
  - r.Header[non-canonical-key] only misses if user code bypasses the
    canonicalization via direct map writes; that's a test-only foot-gun
    and not the regime this middleware runs in.

Per-lookup cost measured side by side on an M4 Pro:

  Header.Values   16.0 ns/op  0 B/op  0 allocs/op
  DirectMap        4.3 ns/op  0 B/op  0 allocs/op

~12 ns saved per request per XFF middleware on the hot path. Test
suite (~70 tests) stays green; walkXFF semantics unchanged.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Example_clientIP: mention fail-closed in the XFF comment

PR #967 fresh review: the inline comment summarizing the XFF middleware
said it "walks right-to-left, skipping trusted entries" but stopped
short of mentioning the fail-closed-on-garbage contract that landed in
5dd2243. Add three words to match the godoc.

Co-authored-by: Cursor <cursoragent@cursor.com>

* TestClientIPFromHeader_MultiValueLastWins: regression-pin wording

PR #967 Copilot review: the godoc on this test still described the
pre-fix behavior in present tense ("Today we surface values[0]"), even
though a8e3dbf already switched the implementation to read
r.Header.Values() and use the last entry.

Reword the godoc to frame the test as a regression pin for the gap
fixed in a8e3dbf -- past-tense bug description, present-tense
post-fix contract. Same body, same test cases, same assertions.

Co-authored-by: Cursor <cursoragent@cursor.com>

* BenchmarkWalkXFF: rename stale rightmostUntrustedXFF reference

PR #967 Copilot review: the BenchmarkWalkXFF godoc referenced
rightmostUntrustedXFF, an internal helper that was consolidated into
the single walkXFF primitive back in 1863339 and no longer exists in
the package. Rename the reference to ClientIPFromXFF (the public
caller whose worst case this benchmark actually exercises). No code
change.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Claude Sonnet 4.7 <noreply@anthropic.com>
2026-05-22 11:16:13 -04:00
.github Bump minimum Go to 1.23, always use request.Pattern (#1048) 2026-02-19 14:13:31 +01:00
_examples Use strings.ReplaceAll where applicable (#1046) 2026-02-08 11:48:22 +01:00
middleware feat: middleware.ClientIP, a replacement for middleware.RealIP (#967) 2026-05-22 11:16:13 -04:00
testdata Simplify go17 and go18 differences to support http2 WrapWriter 2017-01-04 16:29:12 -05:00
.gitignore Ensure a route context is available 2016-05-07 20:54:51 -04:00
chain.go Memory alignment on structs (#589) 2021-02-28 16:49:55 -05:00
CHANGELOG.md v5.0.12 2024-02-16 19:24:11 -05:00
chi.go Fix typo in Route doc comment (#1073) 2026-05-16 16:34:19 +02:00
context.go refactor: iterative wildcard collapsing and add test for consecutive wildcards (#1012) 2025-08-26 14:03:15 +02:00
context_test.go refactor: iterative wildcard collapsing and add test for consecutive wildcards (#1012) 2025-08-26 14:03:15 +02:00
CONTRIBUTING.md docs: Update stale links in docs for contributing (#904) 2024-06-19 17:08:18 +02:00
go.mod Bump minimum Go to 1.23, always use request.Pattern (#1048) 2026-02-19 14:13:31 +01:00
LICENSE Add appengine as a build target for Go 1.8.* targets (#268) 2017-10-06 09:04:20 +02:00
Makefile Update Makefile (#739) 2022-10-18 08:01:24 -04:00
mux.go fix: set Request.Pattern from RoutePattern() (#1097) 2026-05-20 20:15:38 +02:00
mux_test.go update reverseMethodMap in RegisterMethod (#1022) 2025-10-08 18:00:50 +02:00
path_value_test.go Bump minimum Go and use new features (#1017) 2025-09-17 10:51:46 +02:00
pattern_test.go fix: set Request.Pattern from RoutePattern() (#1097) 2026-05-20 20:15:38 +02:00
README.md feat: middleware.ClientIP, a replacement for middleware.RealIP (#967) 2026-05-22 11:16:13 -04:00
SECURITY.md Create SECURITY.md 2023-12-19 21:31:08 -05:00
tree.go Simplify chi.walk with slices.Concat (#1053) 2026-02-19 14:12:24 +01:00
tree_test.go Propagate inline middlewares across mounted subrouters (#1049) 2026-02-12 12:31:51 +01:00

chi

GoDoc Widget

chi is a lightweight, idiomatic and composable router for building Go HTTP services. It's especially good at helping you write large REST API services that are kept maintainable as your project grows and changes. chi is built on the new context package introduced in Go 1.7 to handle signaling, cancelation and request-scoped values across a handler chain.

The focus of the project has been to seek out an elegant and comfortable design for writing REST API servers, written during the development of the Pressly API service that powers our public API service, which in turn powers all of our client-side applications.

The key considerations of chi's design are: project structure, maintainability, standard http handlers (stdlib-only), developer productivity, and deconstructing a large system into many small parts. The core router github.com/go-chi/chi is quite small (less than 1000 LOC), but we've also included some useful/optional subpackages: middleware, render and docgen. We hope you enjoy it too!

Install

go get -u github.com/go-chi/chi/v5

Features

  • Lightweight - cloc'd in ~1000 LOC for the chi router
  • Fast - yes, see benchmarks
  • 100% compatible with net/http - use any http or middleware pkg in the ecosystem that is also compatible with net/http
  • Designed for modular/composable APIs - middlewares, inline middlewares, route groups and sub-router mounting
  • Context control - built on new context package, providing value chaining, cancellations and timeouts
  • Robust - in production at Pressly, Cloudflare, Heroku, 99Designs, and many others (see discussion)
  • Doc generation - docgen auto-generates routing documentation from your source to JSON or Markdown
  • Go.mod support - as of v5, go.mod support (see CHANGELOG)
  • No external dependencies - plain ol' Go stdlib + net/http

Examples

See _examples/ for a variety of examples.

As easy as:

package main

import (
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("welcome"))
	})
	http.ListenAndServe(":3000", r)
}

REST Preview:

Here is a little preview of what routing looks like with chi. Also take a look at the generated routing docs in JSON (routes.json) and in Markdown (routes.md).

I highly recommend reading the source of the examples listed above, they will show you all the features of chi and serve as a good form of documentation.

import (
  //...
  "context"
  "github.com/go-chi/chi/v5"
  "github.com/go-chi/chi/v5/middleware"
)

func main() {
  r := chi.NewRouter()

  // A good base middleware stack
  r.Use(middleware.RequestID)
  r.Use(middleware.ClientIPFromRemoteAddr) // pick one ClientIPFrom* based on your infra, see below
  r.Use(middleware.Logger)
  r.Use(middleware.Recoverer)

  // Set a timeout value on the request context (ctx), that will signal
  // through ctx.Done() that the request has timed out and further
  // processing should be stopped.
  r.Use(middleware.Timeout(60 * time.Second))

  r.Get("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("hi"))
  })

  // RESTy routes for "articles" resource
  r.Route("/articles", func(r chi.Router) {
    r.With(paginate).Get("/", listArticles)                           // GET /articles
    r.With(paginate).Get("/{month}-{day}-{year}", listArticlesByDate) // GET /articles/01-16-2017

    r.Post("/", createArticle)                                        // POST /articles
    r.Get("/search", searchArticles)                                  // GET /articles/search

    // Regexp url parameters:
    r.Get("/{articleSlug:[a-z-]+}", getArticleBySlug)                // GET /articles/home-is-toronto

    // Subrouters:
    r.Route("/{articleID}", func(r chi.Router) {
      r.Use(ArticleCtx)
      r.Get("/", getArticle)                                          // GET /articles/123
      r.Put("/", updateArticle)                                       // PUT /articles/123
      r.Delete("/", deleteArticle)                                    // DELETE /articles/123
    })
  })

  // Mount the admin sub-router
  r.Mount("/admin", adminRouter())

  http.ListenAndServe(":3333", r)
}

func ArticleCtx(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    articleID := chi.URLParam(r, "articleID")
    article, err := dbGetArticle(articleID)
    if err != nil {
      http.Error(w, http.StatusText(404), 404)
      return
    }
    ctx := context.WithValue(r.Context(), "article", article)
    next.ServeHTTP(w, r.WithContext(ctx))
  })
}

func getArticle(w http.ResponseWriter, r *http.Request) {
  ctx := r.Context()
  article, ok := ctx.Value("article").(*Article)
  if !ok {
    http.Error(w, http.StatusText(422), 422)
    return
  }
  w.Write([]byte(fmt.Sprintf("title:%s", article.Title)))
}

// A completely separate router for administrator routes
func adminRouter() http.Handler {
  r := chi.NewRouter()
  r.Use(AdminOnly)
  r.Get("/", adminIndex)
  r.Get("/accounts", adminListAccounts)
  return r
}

func AdminOnly(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    ctx := r.Context()
    perm, ok := ctx.Value("acl.permission").(YourPermissionType)
    if !ok || !perm.IsAdmin() {
      http.Error(w, http.StatusText(403), 403)
      return
    }
    next.ServeHTTP(w, r)
  })
}

Router interface

chi's router is based on a kind of Patricia Radix trie. The router is fully compatible with net/http.

Built on top of the tree is the Router interface:

// Router consisting of the core routing methods used by chi's Mux,
// using only the standard net/http.
type Router interface {
	http.Handler
	Routes

	// Use appends one or more middlewares onto the Router stack.
	Use(middlewares ...func(http.Handler) http.Handler)

	// With adds inline middlewares for an endpoint handler.
	With(middlewares ...func(http.Handler) http.Handler) Router

	// Group adds a new inline-Router along the current routing
	// path, with a fresh middleware stack for the inline-Router.
	Group(fn func(r Router)) Router

	// Route mounts a sub-Router along a `pattern` string.
	Route(pattern string, fn func(r Router)) Router

	// Mount attaches another http.Handler along ./pattern/*
	Mount(pattern string, h http.Handler)

	// Handle and HandleFunc adds routes for `pattern` that matches
	// all HTTP methods.
	Handle(pattern string, h http.Handler)
	HandleFunc(pattern string, h http.HandlerFunc)

	// Method and MethodFunc adds routes for `pattern` that matches
	// the `method` HTTP method.
	Method(method, pattern string, h http.Handler)
	MethodFunc(method, pattern string, h http.HandlerFunc)

	// HTTP-method routing along `pattern`
	Connect(pattern string, h http.HandlerFunc)
	Delete(pattern string, h http.HandlerFunc)
	Get(pattern string, h http.HandlerFunc)
	Head(pattern string, h http.HandlerFunc)
	Options(pattern string, h http.HandlerFunc)
	Patch(pattern string, h http.HandlerFunc)
	Post(pattern string, h http.HandlerFunc)
	Put(pattern string, h http.HandlerFunc)
	Trace(pattern string, h http.HandlerFunc)

	// NotFound defines a handler to respond whenever a route could
	// not be found.
	NotFound(h http.HandlerFunc)

	// MethodNotAllowed defines a handler to respond whenever a method is
	// not allowed.
	MethodNotAllowed(h http.HandlerFunc)
}

// Routes interface adds two methods for router traversal, which is also
// used by the github.com/go-chi/docgen package to generate documentation for Routers.
type Routes interface {
	// Routes returns the routing tree in an easily traversable structure.
	Routes() []Route

	// Middlewares returns the list of middlewares in use by the router.
	Middlewares() Middlewares

	// Match searches the routing tree for a handler that matches
	// the method/path - similar to routing a http request, but without
	// executing the handler thereafter.
	Match(rctx *Context, method, path string) bool
}

Each routing method accepts a URL pattern and chain of handlers. The URL pattern supports named params (ie. /users/{userID}) and wildcards (ie. /admin/*). URL parameters can be fetched at runtime by calling chi.URLParam(r, "userID") for named parameters and chi.URLParam(r, "*") for a wildcard parameter.

Middleware handlers

chi's middlewares are just stdlib net/http middleware handlers. There is nothing special about them, which means the router and all the tooling is designed to be compatible and friendly with any middleware in the community. This offers much better extensibility and reuse of packages and is at the heart of chi's purpose.

Here is an example of a standard net/http middleware where we assign a context key "user" the value of "123". This middleware sets a hypothetical user identifier on the request context and calls the next handler in the chain.

// HTTP middleware setting a value on the request context
func MyMiddleware(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // create new context from `r` request context, and assign key `"user"`
    // to value of `"123"`
    ctx := context.WithValue(r.Context(), "user", "123")

    // call the next handler in the chain, passing the response writer and
    // the updated request object with the new context value.
    //
    // note: context.Context values are nested, so any previously set
    // values will be accessible as well, and the new `"user"` key
    // will be accessible from this point forward.
    next.ServeHTTP(w, r.WithContext(ctx))
  })
}

Request handlers

chi uses standard net/http request handlers. This little snippet is an example of a http.Handler func that reads a user identifier from the request context - hypothetically, identifying the user sending an authenticated request, validated+set by a previous middleware handler.

// HTTP handler accessing data from the request context.
func MyRequestHandler(w http.ResponseWriter, r *http.Request) {
  // here we read from the request context and fetch out `"user"` key set in
  // the MyMiddleware example above.
  user := r.Context().Value("user").(string)

  // respond to the client
  w.Write([]byte(fmt.Sprintf("hi %s", user)))
}

URL parameters

chi's router parses and stores URL parameters right onto the request context. Here is an example of how to access URL params in your net/http handlers. And of course, middlewares are able to access the same information.

// HTTP handler accessing the url routing parameters.
func MyRequestHandler(w http.ResponseWriter, r *http.Request) {
  // fetch the url parameter `"userID"` from the request of a matching
  // routing pattern. An example routing pattern could be: /users/{userID}
  userID := chi.URLParam(r, "userID")

  // fetch `"key"` from the request context
  ctx := r.Context()
  key := ctx.Value("key").(string)

  // respond to the client
  w.Write([]byte(fmt.Sprintf("hi %v, %v", userID, key)))
}

Middlewares

chi comes equipped with an optional middleware package, providing a suite of standard net/http middlewares. Please note, any middleware in the ecosystem that is also compatible with net/http can be used with chi's mux.

Core middlewares


chi/middleware Handler description
AllowContentEncoding Enforces a whitelist of request Content-Encoding headers
AllowContentType Explicit whitelist of accepted request Content-Types
BasicAuth Basic HTTP authentication
Compress Gzip compression for clients that accept compressed responses
ContentCharset Ensure charset for Content-Type request headers
CleanPath Clean double slashes from request path
GetHead Automatically route undefined HEAD requests to GET handlers
Heartbeat Monitoring endpoint to check the servers pulse
Logger Logs the start and end of each request with the elapsed processing time
NoCache Sets response headers to prevent clients from caching
Profiler Easily attach net/http/pprof to your routers
ClientIPFromHeader Capture client IP from a trusted single-IP header (X-Real-IP, CF-Connecting-IP, ...)
ClientIPFromXFF Capture client IP from X-Forwarded-For, skipping listed trusted CIDR prefixes
ClientIPFromXFFTrustedProxies Capture client IP from X-Forwarded-For given a fixed number of trusted proxies
ClientIPFromRemoteAddr Capture client IP from the TCP RemoteAddr (server directly on the public internet)
RealIP Deprecated — vulnerable to IP spoofing; use ClientIPFromXFF or another ClientIPFrom* middleware
Recoverer Gracefully absorb panics and prints the stack trace
RequestID Injects a request ID into the context of each request
RedirectSlashes Redirect slashes on routing paths
RouteHeaders Route handling for request headers
SetHeader Short-hand middleware to set a response header key/value
StripSlashes Strip slashes on routing paths
Sunset Sunset set Deprecation/Sunset header to response
Throttle Puts a ceiling on the number of concurrent requests
Timeout Signals to the request context when the timeout deadline is reached
URLFormat Parse extension from url and put it on request context
WithValue Short-hand middleware to set a key/value on the request context

Choosing a ClientIP middleware

The legacy RealIP middleware is deprecated — it is vulnerable to IP spoofing (GHSA-3fxj-6jh8-hvhx, GHSA-rjr7-jggh-pgcp, GHSA-9g5q-2w5x-hmxf) and mutates r.RemoteAddr. Use one of the four ClientIPFrom* middlewares instead — pick exactly one based on your network setup — and read the resulting IP with GetClientIP (string) or GetClientIPAddr (netip.Addr):

Your setup Use
Directly on the public internet, no proxy middleware.ClientIPFromRemoteAddr
Behind nginx (X-Real-IP), Cloudflare (CF-Connecting-IP), Apache (X-Client-IP) middleware.ClientIPFromHeader("<your-trusted-header>")
Behind one or more proxies whose IP ranges you can list middleware.ClientIPFromXFF("10.0.0.0/8", ...)
Behind a known, fixed number of proxies with dynamic IPs middleware.ClientIPFromXFFTrustedProxies(2)
r := chi.NewRouter()
r.Use(middleware.RequestID)

// Pick exactly one. Examples for common deployments:

// Direct internet exposure (no proxy):
// r.Use(middleware.ClientIPFromRemoteAddr)

// Behind Cloudflare:
// r.Use(middleware.ClientIPFromHeader("CF-Connecting-IP"))

// Behind AWS CloudFront (or any proxy fleet with known CIDRs):
r.Use(middleware.ClientIPFromXFF(
    "13.32.0.0/15",   // CloudFront IPv4
    "52.46.0.0/18",   // CloudFront IPv4
    "2600:9000::/28", // CloudFront IPv6
))

// Behind a known number of proxies with dynamic IPs:
// r.Use(middleware.ClientIPFromXFFTrustedProxies(2))

r.Use(middleware.Logger)
r.Use(middleware.Recoverer)

r.Get("/", func(w http.ResponseWriter, r *http.Request) {
    clientIP := middleware.GetClientIP(r.Context()) // for logs, rate-limit keys, etc.
    _ = clientIP
})

These middlewares never mutate r.RemoteAddr. They store a normalized netip.Addr in the request context — IPv4-mapped IPv6 (::ffff:a.b.c.d) is folded to plain IPv4, and IPv6 zone identifiers carried in headers are stripped, so one logical client maps to a single canonical key for logs, rate limits, and ACLs.

See the per-function godoc for the full semantics of each middleware, and adam-p's "The perils of the 'real' client IP" for the underlying threat model.

Extra middlewares & packages

Please see https://github.com/go-chi for additional packages.


package description
cors Cross-origin resource sharing (CORS)
docgen Print chi.Router routes at runtime
jwtauth JWT authentication
hostrouter Domain/host based request routing
httplog Small but powerful structured HTTP request logging
httprate HTTP request rate limiter
httptracer HTTP request performance tracing library
httpvcr Write deterministic tests for external sources
stampede HTTP request coalescer

context?

context is a tiny pkg that provides simple interface to signal context across call stacks and goroutines. It was originally written by Sameer Ajmani and is available in stdlib since go1.7.

Learn more at https://blog.golang.org/context

and..

Benchmarks

The benchmark suite: https://github.com/pkieltyka/go-http-routing-benchmark

Results as of Nov 29, 2020 with Go 1.15.5 on Linux AMD 3950x

BenchmarkChi_Param          	3075895	        384 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_Param5         	2116603	        566 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_Param20        	 964117	       1227 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_ParamWrite     	2863413	        420 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GithubStatic   	3045488	        395 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GithubParam    	2204115	        540 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GithubAll      	  10000	     113811 ns/op	    81203 B/op    406 allocs/op
BenchmarkChi_GPlusStatic    	3337485	        359 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GPlusParam     	2825853	        423 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GPlus2Params   	2471697	        483 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_GPlusAll       	 194220	       5950 ns/op	     5200 B/op     26 allocs/op
BenchmarkChi_ParseStatic    	3365324	        356 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_ParseParam     	2976614	        404 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_Parse2Params   	2638084	        439 ns/op	      400 B/op      2 allocs/op
BenchmarkChi_ParseAll       	 109567	      11295 ns/op	    10400 B/op     52 allocs/op
BenchmarkChi_StaticAll      	  16846	      71308 ns/op	    62802 B/op    314 allocs/op

Comparison with other routers: https://gist.github.com/pkieltyka/123032f12052520aaccab752bd3e78cc

NOTE: the allocs in the benchmark above are from the calls to http.Request's WithContext(context.Context) method that clones the http.Request, sets the Context() on the duplicated (alloc'd) request and returns it the new request object. This is just how setting context on a request in Go works.

Credits

We'll be more than happy to see your contributions!

Beyond REST

chi is just a http router that lets you decompose request handling into many smaller layers. Many companies use chi to write REST services for their public APIs. But, REST is just a convention for managing state via HTTP, and there's a lot of other pieces required to write a complete client-server system or network of microservices.

Looking beyond REST, I also recommend some newer works in the field:

  • webrpc - Web-focused RPC client+server framework with code-gen
  • gRPC - Google's RPC framework via protobufs
  • graphql - Declarative query language
  • NATS - lightweight pub-sub

License

Copyright (c) 2015-present Peter Kieltyka

Licensed under MIT License