Skip to content

http: set r.Pattern in ServeHTTP before middleware dispatch#3898

Merged
raphael merged 1 commit intov3from
fix/mux-early-pattern
Feb 16, 2026
Merged

http: set r.Pattern in ServeHTTP before middleware dispatch#3898
raphael merged 1 commit intov3from
fix/mux-early-pattern

Conversation

@raphael
Copy link
Copy Markdown
Member

@raphael raphael commented Feb 16, 2026

Summary

Follow-up to #3897. The previous change set r.Pattern inside the handler wrapper, which runs after otelhttp.RequestTraceAttrs reads it. This meant the http.route span attribute was never populated — only the span name was updated.

Root cause

otelhttp reads r.Pattern in RequestTraceAttrs to set http.route at span-start time (before calling next.ServeHTTP). Setting r.Pattern inside the handler is too late for this attribute.

Fix

Override ServeHTTP on the mux to pre-resolve the route via chi.Match and set r.Pattern before chi's middleware chain executes. This ensures that:

  • Middlewares registered via mux.Use() (e.g., otelhttp.NewMiddleware) see r.Pattern at span-start time
  • http.route is set as a span attribute (not just the span name)
  • Metrics also get the route via r.Pattern

The recommended pattern becomes:

mux := goahttp.NewMuxer()
mux.Use(otelhttp.NewMiddleware("service"))

The per-handler r.Pattern setting from #3897 is kept as well — it ensures r.Pattern is correct inside the handler itself.

Test plan

  • New TestRequestPatternInMiddleware — verifies r.Pattern is visible in Use() middlewares (simulating otelhttp)
  • Existing TestRequestPattern — handler-level access still works
  • All mux tests pass

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().
@raphael raphael merged commit 15bb233 into v3 Feb 16, 2026
7 checks passed
@raphael raphael deleted the fix/mux-early-pattern branch February 16, 2026 23:34
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