Skip to content

fix(mux): use context.AfterFunc to prevent premature pool reclamation#1135

Open
jpalafox-12 wants to merge 1 commit into
go-chi:masterfrom
jpalafox-12:master
Open

fix(mux): use context.AfterFunc to prevent premature pool reclamation#1135
jpalafox-12 wants to merge 1 commit into
go-chi:masterfrom
jpalafox-12:master

Conversation

@jpalafox-12

Copy link
Copy Markdown

Closes RoseMark45/chi#1

Fix

Uses context.AfterFunc to defer pool reclamation until the parent request context is cancelled, preventing URL parameter loss when middleware clones the request context.

Changes

  • mux.go: Replace immediate mx.pool.Put(rctx) with context.AfterFunc(r.Context(), ...)
  • mux_test.go: 3 test cases (basic, concurrent, nested sub-routers)

Verification

All existing tests pass. 3 new tests confirm the fix works.

@jpalafox-12
jpalafox-12 marked this pull request as draft July 17, 2026 01:11
When middleware clones the request context with r.WithContext(), the
downstream handler can lose URL parameters because the sync.Pool
reclaims chi.Context immediately after ServeHTTP returns.

Use context.AfterFunc to defer pool reclamation until the parent request
context is cancelled by the HTTP server. This ensures all goroutines
holding cloned contexts have finished before the chi.Context is returned
to the pool.
@jpalafox-12
jpalafox-12 marked this pull request as ready for review July 17, 2026 01:16
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 Context is Replaced in Middleware After Routing

1 participant