英文:
If I use multiple middleware in gin what is the order in which they are executed
问题
如果我使用多个中间件,并且我想在mw2
中使用mw1
的输出,使用ctx.Set
和ctx.Get
,那么中间件的执行顺序是否有定义?例如,在上面的代码片段中,是先调用mw1
还是mw2
?它们的顺序有保证吗?
英文:
If I use multiple middleware and I want to use output of mw1
in mw2
using ctx.Set
and ctx.Get
is there any defined order in which middleware are executed?
func main() {
// Creates a router without any middleware by default
r := gin.New()
// Global middleware
// Logger middleware will write the logs to gin.DefaultWriter even you set with GIN_MODE=release.
// By default gin.DefaultWriter = os.Stdout
r.Use(mw1)
// Recovery middleware recovers from any panics and writes a 500 if there was one.
r.Use(mw2)
// Per route middleware, you can add as many as you desire.
r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
}
For instance in above sniped is mw1
called first, or mw2
is? And is there a guarantee on their ordering?
答案1
得分: 11
它们按照它们添加到路由器的顺序执行。这就是为什么它通常被称为中间件链。
从接受中间件参数的函数的签名中可以看出,如Use
、Group
等,中间件的类型是HandlerFunc
,它们被添加到HandlersChain
中,HandlersChain
的定义如下:
type HandlersChain []HandlerFunc
因此,你可以假设在前一个中间件中设置的上下文值将在后续的中间件中可用:
func main() {
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("key", "foo")
})
r.Use(func(c *gin.Context) {
fmt.Println(c.MustGet("key").(string)) // foo
})
}
英文:
They are executed in the order they are added to the router. That's why it is usually referred as middleware chain.
As you can see from the signature of functions that take middleware args, as Use
, Group
, etc. middlewares have type HandlerFunc
and they are added to the HandlersChain
, which is defined as:
type HandlersChain []HandlerFunc
So you can assume that context values set in a previous middleware will be available in the subsequent ones:
func main() {
r := gin.New()
r.Use(func(c *gin.Context) {
c.Set("key", "foo")
})
r.Use(func(c *gin.Context) {
fmt.Println(c.MustGet("key").(string)) // foo
})
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论