mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-23 11:33:37 +08:00
fix: apply NoMethodSkipHandlers regardless of registration order
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
e08f4d0834
commit
de1749c6f4
8
gin.go
8
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
|
||||
|
||||
@ -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())
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user