Skip to content

Commit

Permalink
fix(header): Allow header according to RFC 7231 (HTTP 405) (#3759)
Browse files Browse the repository at this point in the history
Co-authored-by: Helios <i@shangyes.net>
  • Loading branch information
Crocmagnon and unbyte authored Feb 6, 2024
1 parent e957d1a commit 86ff4a6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
14 changes: 11 additions & 3 deletions gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -633,17 +633,25 @@ func (engine *Engine) handleHTTPRequest(c *Context) {
}

if engine.HandleMethodNotAllowed {
// 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)
for _, tree := range engine.trees {
if tree.method == httpMethod {
continue
}
if value := tree.root.getValue(rPath, nil, c.skippedNodes, unescape); value.handlers != nil {
c.handlers = engine.allNoMethod
serveError(c, http.StatusMethodNotAllowed, default405Body)
return
allowed = append(allowed, tree.method)
}
}
if len(allowed) > 0 {
c.handlers = engine.allNoMethod
c.writermem.Header().Set("Allow", strings.Join(allowed, ", "))
serveError(c, http.StatusMethodNotAllowed, default405Body)
return
}
}

c.handlers = engine.allNoRoute
serveError(c, http.StatusNotFound, default404Body)
}
Expand Down
12 changes: 12 additions & 0 deletions routes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,18 @@ func TestRouteNotAllowedEnabled2(t *testing.T) {
assert.Equal(t, http.StatusMethodNotAllowed, w.Code)
}

func TestRouteNotAllowedEnabled3(t *testing.T) {
router := New()
router.HandleMethodNotAllowed = true
router.GET("/path", func(c *Context) {})
router.POST("/path", func(c *Context) {})
w := PerformRequest(router, http.MethodPut, "/path")
assert.Equal(t, http.StatusMethodNotAllowed, w.Code)
allowed := w.Header().Get("Allow")
assert.Contains(t, allowed, "GET")
assert.Contains(t, allowed, "POST")
}

func TestRouteNotAllowedDisabled(t *testing.T) {
router := New()
router.HandleMethodNotAllowed = false
Expand Down

0 comments on commit 86ff4a6

Please sign in to comment.