如果我在gin中使用多个中间件,它们的执行顺序是怎样的?

huangapple go评论99阅读模式
英文:

If I use multiple middleware in gin what is the order in which they are executed

问题

如果我使用多个中间件,并且我想在mw2中使用mw1的输出,使用ctx.Setctx.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

它们按照它们添加到路由器的顺序执行。这就是为什么它通常被称为中间件链

从接受中间件参数的函数的签名中可以看出,如UseGroup等,中间件的类型是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 
	})
}

huangapple
  • 本文由 发表于 2021年9月23日 15:05:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/69295363.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定