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()) +}