Skip to content

net/http: add Pattern field in Request to return matched pattern info #66618

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions api/next/66405.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pkg net/http, type Request struct, Pattern string #66405
3 changes: 3 additions & 0 deletions doc/next/6-stdlib/99-minor/net/http/66405.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
For inbound requests, the new [Request.Pattern] field contains the [ServeMux]
pattern (if any) that matched the request. This field is not set when
`GODEBUG=httpmuxgo121=1` is set.
4 changes: 4 additions & 0 deletions src/net/http/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,10 @@ type Request struct {
// redirects.
Response *Response

// Pattern is the [ServeMux] pattern that matched the request.
// It is empty if the request was not matched against a pattern.
Pattern string

// ctx is either the client or server context. It should only
// be modified via copying the whole Request using Clone or WithContext.
// It is unexported to prevent people from using Context wrong
Expand Down
5 changes: 4 additions & 1 deletion src/net/http/request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1527,7 +1527,7 @@ func TestPathValueNoMatch(t *testing.T) {
}
}

func TestPathValue(t *testing.T) {
func TestPathValueAndPattern(t *testing.T) {
for _, test := range []struct {
pattern string
url string
Expand Down Expand Up @@ -1568,6 +1568,9 @@ func TestPathValue(t *testing.T) {
t.Errorf("%q, %q: got %q, want %q", test.pattern, name, got, want)
}
}
if r.Pattern != test.pattern {
t.Errorf("pattern: got %s, want %s", r.Pattern, test.pattern)
}
})
server := httptest.NewServer(mux)
defer server.Close()
Expand Down
2 changes: 1 addition & 1 deletion src/net/http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2682,7 +2682,7 @@ func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
if use121 {
h, _ = mux.mux121.findHandler(r)
} else {
h, _, r.pat, r.matches = mux.findHandler(r)
h, r.Pattern, r.pat, r.matches = mux.findHandler(r)
}
h.ServeHTTP(w, r)
}
Expand Down