Skip to content

Commit

Permalink
Panic if regex is invalid
Browse files Browse the repository at this point in the history
  • Loading branch information
vardius committed Feb 26, 2018
1 parent 1f41b50 commit 2d9656a
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 12 deletions.
10 changes: 6 additions & 4 deletions node.go
Expand Up @@ -34,11 +34,13 @@ func (n *node) regexpToString() string {

func (n *node) setRegexp(exp string) {
reg, err := regexp.Compile(exp)
if err == nil {
n.regexp = reg
n.isRegexp = true
n.isWildcard = true
if err != nil {
panic(err)
}

n.regexp = reg
n.isRegexp = true
n.isWildcard = true
}

func (n *node) setRoute(r *route) {
Expand Down
21 changes: 15 additions & 6 deletions router_test.go
Expand Up @@ -172,19 +172,16 @@ func TestOPTIONS(t *testing.T) {

router := New().(*router)
testBasicMethod(t, router, router.OPTIONS, OPTIONS)
}

func TestOPTIONSWithoutHandler(t *testing.T) {
t.Parallel()

router := New().(*router)
handler := &mockHandler{}
router.GET("/x/y", handler)
router.POST("/x/y", handler)

checkIfHasRootRoute(t, router, GET)

w := httptest.NewRecorder()

// test all routes "*" paths
req, err := http.NewRequest(OPTIONS, "*", nil)
if err != nil {
t.Fatal(err)
Expand All @@ -195,6 +192,18 @@ func TestOPTIONSWithoutHandler(t *testing.T) {
if allow := w.Header().Get("Allow"); allow != "POST, GET, OPTIONS" {
t.Errorf("Allow header incorrect value: %s", allow)
}

// test specific path
req, err = http.NewRequest(OPTIONS, "/x/y", nil)
if err != nil {
t.Fatal(err)
}

router.ServeHTTP(w, req)

if allow := w.Header().Get("Allow"); allow != "POST, GET, OPTIONS" {
t.Errorf("Allow header incorrect value: %s", allow)
}
}

func TestNotFound(t *testing.T) {
Expand Down Expand Up @@ -483,7 +492,7 @@ func TestChainCalls(t *testing.T) {
router := New().(*router)

serverd := false
router.GET("/users/{user}/starred", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
router.GET("/users/{user:[a-z0-9]+)}/starred", http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
serverd = true

params, ok := FromContext(r.Context())
Expand Down
4 changes: 2 additions & 2 deletions tree.go
Expand Up @@ -65,7 +65,7 @@ func (t *tree) getByID(id string) *node {
}

for _, child := range t.regexps {
if child.regexp.MatchString(id) {
if child.regexp != nil && child.regexp.MatchString(id) {
return child
}
}
Expand Down Expand Up @@ -96,7 +96,7 @@ func (t *tree) getByPath(path string) (*node, string, string) {
}

for _, child := range t.regexps {
if child.regexp.MatchString(part) {
if child.regexp != nil && child.regexp.MatchString(part) {
return child, part, path[len(part):]
}
}
Expand Down

0 comments on commit 2d9656a

Please sign in to comment.