Add tests for regexp variables in query strings
Fix how regular expression gets built for query string so that order of parameters is always preserved
This commit is contained in:
18
mux_test.go
18
mux_test.go
@@ -489,6 +489,24 @@ func TestQueries(t *testing.T) {
|
|||||||
path: "",
|
path: "",
|
||||||
shouldMatch: true,
|
shouldMatch: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
title: "Queries route with regexp pattern, match",
|
||||||
|
route: new(Route).Queries("foo", "{v1:[0-9]+}"),
|
||||||
|
request: newRequest("GET", "http://localhost?foo=10"),
|
||||||
|
vars: map[string]string{"v1": "10"},
|
||||||
|
host: "",
|
||||||
|
path: "",
|
||||||
|
shouldMatch: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: "Queries route with regexp pattern, regexp does not match",
|
||||||
|
route: new(Route).Queries("foo", "{v1:[0-9]+}"),
|
||||||
|
request: newRequest("GET", "http://localhost?foo=a"),
|
||||||
|
vars: map[string]string{},
|
||||||
|
host: "",
|
||||||
|
path: "",
|
||||||
|
shouldMatch: false,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
|
|||||||
14
route.go
14
route.go
@@ -339,15 +339,19 @@ func (r *Route) PathPrefix(tpl string) *Route {
|
|||||||
// - {name:pattern} matches the given regexp pattern.
|
// - {name:pattern} matches the given regexp pattern.
|
||||||
|
|
||||||
func (r *Route) Queries(pairs ...string) *Route {
|
func (r *Route) Queries(pairs ...string) *Route {
|
||||||
|
length := len(pairs)
|
||||||
|
if length%2 != 0 {
|
||||||
|
r.err = fmt.Errorf(
|
||||||
|
"mux: number of parameters must be multiple of 2, got %v", pairs)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
var queries map[string]string
|
for i := 0; i < length; i += 2 {
|
||||||
buf.WriteString("")
|
buf.WriteString(fmt.Sprintf("%s=%s&", pairs[i], pairs[i+1]))
|
||||||
queries, r.err = mapFromPairs(pairs...)
|
|
||||||
for k, v := range queries {
|
|
||||||
buf.WriteString(fmt.Sprintf("%s=%s&", k, v))
|
|
||||||
}
|
}
|
||||||
tpl := strings.TrimRight(buf.String(), "&")
|
tpl := strings.TrimRight(buf.String(), "&")
|
||||||
r.err = r.addRegexpMatcher(tpl, false, true, true)
|
r.err = r.addRegexpMatcher(tpl, false, true, true)
|
||||||
|
|
||||||
return r
|
return r
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user