Merge 700d4416aa8600516b37e25f7c3ad1a2990fbbcf into d3ffc9985281dcf4d3bef604cce4e662b1a327a6

This commit is contained in:
Gavin Zhang 2026-04-04 19:22:56 +08:00 committed by GitHub
commit eae386974d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 38 additions and 2 deletions

View File

@ -459,6 +459,10 @@ func main() {
} }
``` ```
Attach global middleware before registering routes. Routes added before a `Use()` call are not
retroactively wrapped, while `404` and `405` handlers are rebuilt from the current global
middleware chain.
### Custom Middleware ### Custom Middleware
```go ```go

5
gin.go
View File

@ -334,8 +334,9 @@ func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
engine.rebuild405Handlers() engine.rebuild405Handlers()
} }
// Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be // Use attaches a global middleware to the router. Middleware attached through Use() is included
// included in the handlers chain for every single request. Even 404, 405, static files... // in the handlers chain for routes registered after the call. For 404 and 405 requests, Gin
// rebuilds the handler chain from the current middleware set.
// For example, this is the right place for a logger or error management middleware. // For example, this is the right place for a logger or error management middleware.
func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes { func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
engine.RouterGroup.Use(middleware...) engine.RouterGroup.Use(middleware...)

View File

@ -570,6 +570,37 @@ func TestRebuild404Handlers(t *testing.T) {
compareFunc(t, router.allNoRoute[1], middleware0) compareFunc(t, router.allNoRoute[1], middleware0)
} }
func TestUseOnlyAppliesToRoutesRegisteredAfterIt(t *testing.T) {
signature := ""
router := New()
router.GET("/before", func(c *Context) {
signature += "A"
c.Status(http.StatusNoContent)
})
router.Use(func(c *Context) {
signature += "M"
c.Next()
signature += "N"
})
router.GET("/after", func(c *Context) {
signature += "B"
c.Status(http.StatusNoContent)
})
w := PerformRequest(router, http.MethodGet, "/before")
assert.Equal(t, http.StatusNoContent, w.Code)
assert.Equal(t, "A", signature)
signature = ""
w = PerformRequest(router, http.MethodGet, "/after")
assert.Equal(t, http.StatusNoContent, w.Code)
assert.Equal(t, "MBN", signature)
}
func TestNoMethodWithGlobalHandlers(t *testing.T) { func TestNoMethodWithGlobalHandlers(t *testing.T) {
var middleware0 HandlerFunc = func(c *Context) {} var middleware0 HandlerFunc = func(c *Context) {}
var middleware1 HandlerFunc = func(c *Context) {} var middleware1 HandlerFunc = func(c *Context) {}