From c6e32742c4b733230c82627571b423de45997c24 Mon Sep 17 00:00:00 2001 From: "Chen.Zhidong" Date: Fri, 17 May 2024 00:22:50 +0800 Subject: [PATCH] net/http: add Request.Pattern --- api/next/66405.txt | 1 + doc/next/6-stdlib/99-minor/net/http/66405.md | 3 +++ src/net/http/request.go | 4 ++++ src/net/http/request_test.go | 5 ++++- src/net/http/server.go | 2 +- 5 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 api/next/66405.txt create mode 100644 doc/next/6-stdlib/99-minor/net/http/66405.md diff --git a/api/next/66405.txt b/api/next/66405.txt new file mode 100644 index 00000000000..0b39494f92b --- /dev/null +++ b/api/next/66405.txt @@ -0,0 +1 @@ +pkg net/http, type Request struct, Pattern string #66405 diff --git a/doc/next/6-stdlib/99-minor/net/http/66405.md b/doc/next/6-stdlib/99-minor/net/http/66405.md new file mode 100644 index 00000000000..c827b4b2192 --- /dev/null +++ b/doc/next/6-stdlib/99-minor/net/http/66405.md @@ -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. diff --git a/src/net/http/request.go b/src/net/http/request.go index 345ba3d4eb4..96a340725db 100644 --- a/src/net/http/request.go +++ b/src/net/http/request.go @@ -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 diff --git a/src/net/http/request_test.go b/src/net/http/request_test.go index 8c8116123cb..439cc0465fa 100644 --- a/src/net/http/request_test.go +++ b/src/net/http/request_test.go @@ -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 @@ -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() diff --git a/src/net/http/server.go b/src/net/http/server.go index 32b4130c222..9af897a77dc 100644 --- a/src/net/http/server.go +++ b/src/net/http/server.go @@ -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) }