From 0a0d6a1b2a0c75b931495697ce6a2182f810ffb3 Mon Sep 17 00:00:00 2001 From: Raphael Simon Date: Mon, 26 May 2014 20:20:14 -0700 Subject: [PATCH] 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 --- mux_test.go | 18 ++++++++++++++++++ route.go | 14 +++++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/mux_test.go b/mux_test.go index c133d6c..48506bf 100644 --- a/mux_test.go +++ b/mux_test.go @@ -489,6 +489,24 @@ func TestQueries(t *testing.T) { path: "", 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 { diff --git a/route.go b/route.go index afe3e7f..00989bf 100644 --- a/route.go +++ b/route.go @@ -339,15 +339,19 @@ func (r *Route) PathPrefix(tpl string) *Route { // - {name:pattern} matches the given regexp pattern. 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 queries map[string]string - buf.WriteString("") - queries, r.err = mapFromPairs(pairs...) - for k, v := range queries { - buf.WriteString(fmt.Sprintf("%s=%s&", k, v)) + for i := 0; i < length; i += 2 { + buf.WriteString(fmt.Sprintf("%s=%s&", pairs[i], pairs[i+1])) } tpl := strings.TrimRight(buf.String(), "&") r.err = r.addRegexpMatcher(tpl, false, true, true) + return r }