From de1749c6f41a42e5a870d8a9d2aaac1f9a71aea9 Mon Sep 17 00:00:00 2001 From: RubenPari Date: Sun, 4 Oct 2026 22:23:36 +0200 Subject: [PATCH] fix: apply NoMethodSkipHandlers regardless of registration order Co-Authored-By: Claude Opus 5.5 (1M context) --- gin.go | 8 +++----- middleware_test.go | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/gin.go b/gin.go index 0b04040f..dc43a4f8 100644 --- a/gin.go +++ b/gin.go @@ -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 diff --git a/middleware_test.go b/middleware_test.go index 78080322..af417cec 100644 --- a/middleware_test.go +++ b/middleware_test.go @@ -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()) +}