Merge c8a048340895e685eeaa4a161a359051f60a9603 into 3b08cd7235bd5ad2f055aa9e38135f111f6c5926

This commit is contained in:
Ruben Pari 2026-09-19 17:15:03 -04:00 committed by GitHub
commit 1457659bc0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 49 additions and 0 deletions

11
gin.go
View File

@ -129,6 +129,13 @@ type Engine struct {
// handler.
HandleMethodNotAllowed bool
// NoMethodSkipHandlers when true, the 405 chain is only Engine.NoMethod
// 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
// match those stored at `(*gin.Engine).RemoteIPHeaders`. If no IP was
// fetched, it falls back to the IP obtained from
@ -381,6 +388,10 @@ func (engine *Engine) rebuild404Handlers() {
}
func (engine *Engine) rebuild405Handlers() {
if engine.NoMethodSkipHandlers {
engine.allNoMethod = engine.noMethod
return
}
engine.allNoMethod = engine.combineHandlers(engine.noMethod)
}

View File

@ -251,3 +251,41 @@ func TestMiddlewareWrite(t *testing.T) {
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Equal(t, strings.ReplaceAll("hola\n<map><foo>bar</foo></map>{\"foo\":\"bar\"}{\"foo\":\"bar\"}event:test\ndata:message\n\n", " ", ""), strings.ReplaceAll(w.Body.String(), " ", ""))
}
func TestNoMethodSkipHandlers(t *testing.T) {
router := New()
router.HandleMethodNotAllowed = true
router.NoMethodSkipHandlers = 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.POST("/ping", func(c *Context) {
c.String(http.StatusOK, "pong")
})
w := PerformRequest(router, http.MethodGet, "/ping")
assert.Equal(t, http.StatusMethodNotAllowed, w.Code)
assert.Equal(t, "no method", w.Body.String())
}
func TestNoMethodIncludesGlobalMiddlewareByDefault(t *testing.T) {
router := New()
router.HandleMethodNotAllowed = true
// NoMethodSkipHandlers left false
router.Use(func(c *Context) {
c.String(http.StatusBadRequest, "mw")
c.Abort()
})
router.NoMethod(func(c *Context) {
c.String(http.StatusMethodNotAllowed, "no method")
})
router.POST("/ping", func(c *Context) { c.Status(http.StatusOK) })
w := PerformRequest(router, http.MethodGet, "/ping")
assert.Equal(t, http.StatusBadRequest, w.Code)
assert.Equal(t, "mw", w.Body.String())
}