Skip to content

middleware: build Maybe handler once - #1197

Open
lowgame wants to merge 1 commit into
go-chi:masterfrom
lowgame:fix-maybe-middleware-build-007d0155
Open

lowgame wants to merge 1 commit into
go-chi:masterfrom
lowgame:fix-maybe-middleware-build-007d0155

Conversation

@lowgame

@lowgame lowgame commented Oct 1, 2026

Copy link
Copy Markdown

Reproduction

middleware.Maybe called the middleware constructor once per matching request. A stateful constructor therefore reported two builds after serving two requests through the same handler.

The added TestMaybeBuildsMiddlewareOnce fails on the previous implementation with:

middleware was built 2 times, want 1

Root cause

mw(next) was evaluated inside the request handler instead of when the middleware chain was assembled.

Solution

Build the wrapped handler once in Maybe's outer closure, then use that handler whenever the request predicate matches. The predicate is still evaluated independently for every request, and nonmatching requests still go directly to next.

Tests

  • GOTOOLCHAIN=go1.25.1 go test ./middleware -run '^TestMaybeBuildsMiddlewareOnce$' -count=20
  • GOTOOLCHAIN=go1.25.1 go test -race ./middleware
  • GOTOOLCHAIN=go1.25.1 go test -race .
  • GOTOOLCHAIN=go1.25.1 go vet ./...
  • git diff --check

This branch has not been deployed

No deployments
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.

1 participant