Skip to content

Commit

Permalink
fix(gin): Do not panic when handling method not allowed on empty tree (
Browse files Browse the repository at this point in the history
…#4003)

Signed-off-by: Pierre-Henri Symoneaux <[email protected]>
  • Loading branch information
phsym authored Jun 22, 2024
1 parent 9c081de commit 626d55b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
2 changes: 1 addition & 1 deletion gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -687,7 +687,7 @@ func (engine *Engine) handleHTTPRequest(c *Context) {
break
}

if engine.HandleMethodNotAllowed {
if engine.HandleMethodNotAllowed && len(t) > 0 {
// According to RFC 7231 section 6.5.5, MUST generate an Allow header field in response
// containing a list of the target resource's currently supported methods.
allowed := make([]string, 0, len(t)-1)
Expand Down
11 changes: 11 additions & 0 deletions gin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -754,3 +754,14 @@ func TestCustomUnmarshalStruct(t *testing.T) {
assert.Equal(t, 200, w.Code)
assert.Equal(t, `"2000/01/01"`, w.Body.String())
}

// Test the fix for https://github.com/gin-gonic/gin/issues/4002
func TestMethodNotAllowedNoRoute(t *testing.T) {
g := New()
g.HandleMethodNotAllowed = true

req := httptest.NewRequest("GET", "/", nil)
resp := httptest.NewRecorder()
assert.NotPanics(t, func() { g.ServeHTTP(resp, req) })
assert.Equal(t, http.StatusNotFound, resp.Code)
}

0 comments on commit 626d55b

Please sign in to comment.