Skip to content

Commit

Permalink
net/http: add Pattern field in Request to return matched pattern info
Browse files Browse the repository at this point in the history
Fixes #66405

Change-Id: Icd80944b6ca081aa7addd4fb85d2b3c29b6c9542
GitHub-Last-Rev: c6e3274
GitHub-Pull-Request: #66618
Reviewed-on: https://go-review.googlesource.com/c/go/+/574997
Reviewed-by: Damien Neil <[email protected]>
Reviewed-by: Jonathan Amsterdam <[email protected]>
LUCI-TryBot-Result: Go LUCI <[email protected]>
  • Loading branch information
sillydong authored and jba committed May 16, 2024
1 parent 06b4578 commit a523152
Show file tree
Hide file tree
Showing 5 changed files with 13 additions and 2 deletions.
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 @@ -1576,6 +1576,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 @@ -2703,7 +2703,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

0 comments on commit a523152

Please sign in to comment.