Browse Source

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
pull/55/head
Raphael Simon 12 years ago
parent
commit
0a0d6a1b2a
  1. 18
      mux_test.go
  2. 14
      route.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

@ -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
} }

Loading…
Cancel
Save