Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/doc.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

```go
Expand Down
5 changes: 3 additions & 2 deletions gin.go
Original file line number Diff line number Diff line change
Expand Up @@ -334,8 +334,9 @@ func (engine *Engine) NoMethod(handlers ...HandlerFunc) {
engine.rebuild405Handlers()
}

// Use attaches a global middleware to the router. i.e. the middleware attached through Use() will be
// included in the handlers chain for every single request. Even 404, 405, static files...
// Use attaches a global middleware to the router. Middleware attached through Use() is included
// 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.
func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {
engine.RouterGroup.Use(middleware...)
Expand Down
31 changes: 31 additions & 0 deletions gin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -570,6 +570,37 @@ func TestRebuild404Handlers(t *testing.T) {
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) {
var middleware0 HandlerFunc = func(c *Context) {}
var middleware1 HandlerFunc = func(c *Context) {}
Expand Down
Loading