Skip to content

Commit 7859137

Browse files
authored
Allow multiple whitespace between method & pattern (#1013)
Allow separating the method and pattern with [ \t]+, this matches the stdlib change that was made in golang/go@7b583fd The rationale is the same as the stdlib issue, it allows you to visually line up patterns with variable-width methods: r.Handle("GET /my-route", handler1) r.Handle("POST /my-route", handler2) r.Handle("DELETE /my-route", handler3) In general aligning ourselves with the stdlib brings less surprise for end users.
1 parent 80d8da2 commit 7859137

File tree

2 files changed

+12
-7
lines changed

2 files changed

+12
-7
lines changed

mux.go

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,8 @@ func (mx *Mux) Use(middlewares ...func(http.Handler) http.Handler) {
107107
// Handle adds the route `pattern` that matches any http method to
108108
// execute the `handler` http.Handler.
109109
func (mx *Mux) Handle(pattern string, handler http.Handler) {
110-
if method, rest, found := strings.Cut(pattern, " "); found {
110+
if i := strings.IndexAny(pattern, " \t"); i >= 0 {
111+
method, rest := pattern[:i], strings.TrimLeft(pattern[i+1:], " \t")
111112
mx.Method(method, rest, handler)
112113
return
113114
}
@@ -118,12 +119,7 @@ func (mx *Mux) Handle(pattern string, handler http.Handler) {
118119
// HandleFunc adds the route `pattern` that matches any http method to
119120
// execute the `handlerFn` http.HandlerFunc.
120121
func (mx *Mux) HandleFunc(pattern string, handlerFn http.HandlerFunc) {
121-
if method, rest, found := strings.Cut(pattern, " "); found {
122-
mx.Method(method, rest, handlerFn)
123-
return
124-
}
125-
126-
mx.handle(mALL, pattern, handlerFn)
122+
mx.Handle(pattern, handlerFn)
127123
}
128124

129125
// Method adds the route `pattern` that matches `method` http method to

mux_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,15 @@ func TestMuxHandlePatternValidation(t *testing.T) {
668668
expectedBody: "with-prefix POST",
669669
expectedStatus: http.StatusOK,
670670
},
671+
{
672+
name: "Valid pattern with multiple whitespace after method",
673+
pattern: "PATCH \t /",
674+
shouldPanic: false,
675+
method: "PATCH",
676+
path: "/",
677+
expectedBody: "extended-whitespace PATCH",
678+
expectedStatus: http.StatusOK,
679+
},
671680
// Invalid patterns
672681
{
673682
name: "Invalid pattern with no method",

0 commit comments

Comments
 (0)