Skip to content

Commit

Permalink
fix: notfound handler was called although route exists
Browse files Browse the repository at this point in the history
  • Loading branch information
sknr committed Jan 15, 2024
1 parent 1709e1d commit d704aaf
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
9 changes: 5 additions & 4 deletions node.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,7 @@ func (n *node) _findRoute(meth, path string) (*node, *routeHandler, int) {
if handler != nil {
return node, handler, wildcardLen
}
if node != nil {
found = node
}
found = node
}
}
}
Expand All @@ -154,9 +152,12 @@ func (n *node) _findRoute(meth, path string) (*node, *routeHandler, int) {
if n.colon != nil {
if i := strings.IndexByte(path, '/'); i > 0 {
node, handler, wildcardLen := n.colon._findRoute(meth, path[i:])
if handler != nil {
if node != nil && handler != nil {
return node, handler, wildcardLen
}
if found == nil {
found = node
}
} else if n.colon.handlerMap != nil {
if handler := n.colon.handlerMap.Get(meth); handler != nil {
return n.colon, handler, 0
Expand Down
22 changes: 18 additions & 4 deletions router_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,12 +108,15 @@ func TestNotFound(t *testing.T) {
require.Equal(t, http.StatusNotFound, w.Code)
require.Equal(t, 0, calledNotFound)

// Now try with a custome handler.
// Now try with a custom handler.
router = New(WithNotFoundHandler(notFoundHandler))
router.GET("/user/abc", simpleHandler)

w = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/abc/", nil)

router.ServeHTTP(w, req)
require.Equal(t, http.StatusNotFound, w.Code)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, 1, calledNotFound)
}

Expand All @@ -127,6 +130,7 @@ func TestMethodNotAllowed(t *testing.T) {

router := New()
router.POST("/abc", simpleHandler)
router.GET("/abc/:id/def/:sub_id", simpleHandler)

w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/abc", nil)
Expand All @@ -135,12 +139,22 @@ func TestMethodNotAllowed(t *testing.T) {
require.Equal(t, http.StatusMethodNotAllowed, w.Code)
require.Equal(t, 0, calledMethodNotAllowed)

// Now try with a custome handler.
w = httptest.NewRecorder()
req, _ = http.NewRequest("POST", "/abc/1/def/2", nil)

router.ServeHTTP(w, req)
require.Equal(t, http.StatusMethodNotAllowed, w.Code)
require.Equal(t, 0, calledMethodNotAllowed)

// Now try with a custom handler.
router = New(WithMethodNotAllowedHandler(methodNotAllowedHandler))
router.POST("/abc", simpleHandler)

w = httptest.NewRecorder()
req, _ = http.NewRequest("GET", "/abc", nil)

router.ServeHTTP(w, req)
require.Equal(t, http.StatusMethodNotAllowed, w.Code)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, 1, calledMethodNotAllowed)
}

Expand Down

0 comments on commit d704aaf

Please sign in to comment.