Skip to content

Fix URL parameter loss when middleware rewrites request path - #5

Open
wasim-builds wants to merge 1 commit into
madalynerlge2:mainfrom
wasim-builds:fix-url-param-loss
Open

Fix URL parameter loss when middleware rewrites request path#5
wasim-builds wants to merge 1 commit into
madalynerlge2:mainfrom
wasim-builds:fix-url-param-loss

Conversation

@wasim-builds

Copy link
Copy Markdown

Summary

Fixes #1

When middleware rewrites r.URL.Path (e.g., stripping prefixes or normalizing paths), chi's cached RoutePath becomes stale and URL parameters get lost. chi.URLParam(r, "key") returns empty strings because route matching happens against the old path.

Root Cause

chi caches the request path in rctx.RoutePath at the start of ServeHTTP. When middleware modifies r.URL.Path between that point and when routeHTTP does pattern matching, the stale cache causes wrong route matches and lost parameters.

Fix

Added SyncPath(r) in two key locations:

  1. ServeHTTP — resyncs after getting the routing context (both for fresh requests and parent-router contexts)
  2. routeHTTP — resyncs right before pattern matching, catching any middleware mutations

Added URLPath and RawPath fields to chi.Context to track the last-seen r.URL.Path and detect when it's been mutated.

Test

go test -run TestURLParameterPreservationOnPathRewrite -v ./...
=== RUN   TestURLParameterPreservationOnPathRewrite
--- PASS: TestURLParameterPreservationOnPathRewrite (0.00s)
PASS

Backward Compatibility

  • Zero overhead when r.URL.Path is not modified (string comparison short-circuits)
  • Existing handlers calling chi.URLParam(r, "key") require zero changes
  • The sync pool pattern and middleware chain are preserved exactly as upstream

When middleware rewrites r.URL.Path (e.g., stripping prefixes), chi's
cached RoutePath becomes stale and URL parameters get lost.

Changes:
- Add URLPath/RawPath fields to chi.Context for tracking path mutations
- Add SyncPath(r) method to detect and resync RoutePath after middleware
- Call SyncPath in ServeHTTP (after pool fetch) and routeHTTP (before matching)
- Add test verifying URL params survive a middleware path rewrite

Fixes madalynerlge2#1
@wasim-builds

Copy link
Copy Markdown
Author

Hi, this PR fixes the URL parameter loss bug described in #1. The fix resyncs RoutePath in chi.go when middleware rewrites the request path. Happy to make any changes or add tests if needed!

@wasim-builds

Copy link
Copy Markdown
Author

/claim #1

@opirebot

opirebot Bot commented Jul 29, 2026

Copy link
Copy Markdown

😅 Unfortunately there are no rewards left to claim in this issue!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

🎯 Fix URL Parameter Loss When Request.URL.Path is Rewritten by Middleware

1 participant