http: set r.Pattern in ServeHTTP before middleware dispatch#3898
Merged
Conversation
The previous commit set r.Pattern inside the handler wrapper, which runs after otelhttp reads it in RequestTraceAttrs. This meant the http.route span attribute was never populated. Override ServeHTTP to pre-resolve the route via chi.Match and set r.Pattern before chi's middleware chain runs. This ensures that observability middleware registered via mux.Use() — such as otelhttp.NewMiddleware — can read r.Pattern at span-start time to set http.route on both spans and metrics. Add TestRequestPatternInMiddleware to verify r.Pattern is visible to middlewares registered via Use().
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Follow-up to #3897. The previous change set
r.Patterninside the handler wrapper, which runs afterotelhttp.RequestTraceAttrsreads it. This meant thehttp.routespan attribute was never populated — only the span name was updated.Root cause
otelhttp reads
r.PatterninRequestTraceAttrsto sethttp.routeat span-start time (before callingnext.ServeHTTP). Settingr.Patterninside the handler is too late for this attribute.Fix
Override
ServeHTTPon the mux to pre-resolve the route viachi.Matchand setr.Patternbefore chi's middleware chain executes. This ensures that:mux.Use()(e.g.,otelhttp.NewMiddleware) seer.Patternat span-start timehttp.routeis set as a span attribute (not just the span name)r.PatternThe recommended pattern becomes:
The per-handler
r.Patternsetting from #3897 is kept as well — it ensuresr.Patternis correct inside the handler itself.Test plan
TestRequestPatternInMiddleware— verifiesr.Patternis visible inUse()middlewares (simulating otelhttp)TestRequestPattern— handler-level access still works