[bugfix] fail fast if regex is incorrectly specified using capturing groups. (#218)

This commit is contained in:
Adam Eijdenberg
2017-01-19 00:43:44 +11:00
committed by Matt Silverlock
parent cafdb65e9e
commit 392c28fe23
3 changed files with 22 additions and 0 deletions

5
doc.go
View File

@@ -57,6 +57,11 @@ calling mux.Vars():
vars := mux.Vars(request) vars := mux.Vars(request)
category := vars["category"] category := vars["category"]
Note that if any capturing groups are present, mux will panic() during parsing. To prevent
this, convert any capturing groups to non-capturing, e.g. change "/{sort:(asc|desc)}" to
"/{sort:(?:asc|desc)}". This is a change from prior versions which behaved unpredictably
when capturing groups were present.
And this is all you need to know about the basic usage. More advanced options And this is all you need to know about the basic usage. More advanced options
are explained below. are explained below.

View File

@@ -1389,6 +1389,16 @@ func TestSubrouterErrorHandling(t *testing.T) {
} }
} }
// See: https://github.com/gorilla/mux/issues/200
func TestPanicOnCapturingGroups(t *testing.T) {
defer func() {
if recover() == nil {
t.Errorf("(Test that capturing groups now fail fast) Expected panic, however test completed sucessfully.\n")
}
}()
NewRouter().NewRoute().Path("/{type:(promo|special)}/{promoId}.json")
}
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Helpers // Helpers
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------

View File

@@ -109,6 +109,13 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash,
if errCompile != nil { if errCompile != nil {
return nil, errCompile return nil, errCompile
} }
// Check for capturing groups which used to work in older versions
if reg.NumSubexp() != len(idxs)/2 {
panic(fmt.Sprintf("route %s contains capture groups in its regexp. ", template) +
"Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)")
}
// Done! // Done!
return &routeRegexp{ return &routeRegexp{
template: template, template: template,