fix: apply NoMethodSkipHandlers regardless of registration order

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
RubenPari 2026-10-04 22:23:36 +02:00
parent e08f4d0834
commit de1749c6f4
2 changed files with 21 additions and 5 deletions

8
gin.go
View File

@ -133,7 +133,6 @@ type Engine struct {
// handlers — global middleware from Engine.Use is not prepended. Default
// false keeps historical behavior (logger/recovery still run on 405).
// Only applies when HandleMethodNotAllowed is true.
// Set this before Use/NoMethod (rebuild happens on those calls).
NoMethodSkipHandlers bool
// ForwardedByClientIP if enabled, client IP will be parsed from the request's headers that
@ -388,10 +387,6 @@ func (engine *Engine) rebuild404Handlers() {
}
func (engine *Engine) rebuild405Handlers() {
if engine.NoMethodSkipHandlers {
engine.allNoMethod = engine.noMethod
return
}
engine.allNoMethod = engine.combineHandlers(engine.noMethod)
}
@ -789,6 +784,9 @@ func (engine *Engine) handleHTTPRequest(c *Context) {
}
if len(allowed) > 0 {
c.handlers = engine.allNoMethod
if engine.NoMethodSkipHandlers {
c.handlers = engine.noMethod
}
c.writermem.Header().Set("Allow", strings.Join(allowed, ", "))
serveError(c, http.StatusMethodNotAllowed, default405Body)
return

View File

@ -289,3 +289,21 @@ func TestNoMethodIncludesGlobalMiddlewareByDefault(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Equal(t, "mw", w.Body.String())
}
func TestNoMethodSkipHandlersSetAfterRegistration(t *testing.T) {
router := New()
router.HandleMethodNotAllowed = true
router.Use(func(c *Context) {
c.String(http.StatusBadRequest, "mw")
c.Abort()
})
router.NoMethod(func(c *Context) {
c.String(http.StatusMethodNotAllowed, "no method")
})
router.NoMethodSkipHandlers = true
router.POST("/ping", func(c *Context) { c.Status(http.StatusOK) })
w := PerformRequest(router, http.MethodGet, "/ping")
assert.Equal(t, http.StatusMethodNotAllowed, w.Code)
assert.Equal(t, "no method", w.Body.String())
}