Skip to content

Commit edfe8fd

Browse files
committed
Fix issue 200, fail fast if regex is incorrectly specified using capturing groups.
1 parent b128961 commit edfe8fd

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

doc.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@ calling mux.Vars():
5757
vars := mux.Vars(request)
5858
category := vars["category"]
5959
60+
Note that if any capturing groups are present, mux will panic() during parsing. To prevent
61+
this, convert any capturing groups to non-capturing, e.g. change "/{sort:(asc|desc)}" to
62+
"/{sort:(?:asc|desc)}". This is a change from prior versions which behaved unpredictably
63+
when capturing groups were present.
64+
6065
And this is all you need to know about the basic usage. More advanced options
6166
are explained below.
6267

mux_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1389,6 +1389,16 @@ func TestSubrouterErrorHandling(t *testing.T) {
13891389
}
13901390
}
13911391

1392+
// See: https://github.com/gorilla/mux/issues/200
1393+
func TestPanicOnCapturingGroups(t *testing.T) {
1394+
defer func() {
1395+
if recover() == nil {
1396+
t.Errorf("(Test that capturing groups now fail fast) Expected panic, however test completed sucessfully.\n")
1397+
}
1398+
}()
1399+
NewRouter().NewRoute().Path("/{type:(promo|special)}/{promoId}.json")
1400+
}
1401+
13921402
// ----------------------------------------------------------------------------
13931403
// Helpers
13941404
// ----------------------------------------------------------------------------

regexp.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,13 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash,
109109
if errCompile != nil {
110110
return nil, errCompile
111111
}
112+
113+
// Check for capturing groups which used to work in older versions
114+
if reg.NumSubexp() != len(idxs)/2 {
115+
panic(fmt.Sprintf("route %s contains capture groups in its regexp. ", template) +
116+
"Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)")
117+
}
118+
112119
// Done!
113120
return &routeRegexp{
114121
template: template,

0 commit comments

Comments
 (0)