现有如下代码:
func main(){
router := gin.New()
mid1 := func(c * gin.Context){
fmt.Println("mid1 start")
c.Next()
fmt.Println("mid1 end")
}
mid2 := func(c * gin.Context){
fmt.Println("mid2 start")
c.Next()
fmt.Println("mid2 end")
}
mid3 := func(c * gin.Context){
fmt.Println("mid3 start")
c.Next()
fmt.Println("mid3 end")
}
router.Use(mid1,mid2,mid3)
router.GET("/",func(c * gin.Context){
fmt.Println("process get request")
c.JSON(http.StatusOK,"hello")
})
router.Run()
}
在访问127.0.0.1:8080
时发生了什么?
首先,浏览器发出GET请求,gin会调用它的处理请求的函数:
// gin.go
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// 这里使用了对象池
c := engine.pool.Get().(*Context)
// 这里有一个细节就是Get对象后做初始化
c.writermem.reset(w)
c.Request = req
c.reset()
engine.handleHTTPRequest(c) // 我们要找的处理HTTP请求的函数
engine.pool.Put(c) // 处理完请求后将对象放回池子
}
注意其中的handleHTTPRequest
函数:
// gin.go
func (engine *Engine) handleHTTPRequest(c *Context) {
// liwenzhou.com...
// 根据请求方法找到对应的路由树
t := engine.trees
for i, tl := 0, len(t); i < tl; i++ {
if t[i].method != httpMethod {
continue
}
root := t[i].root
// 在路由树中根据path查找
value := root.getValue(rPath, c.Params, unescape)
if value.handlers != nil {
c.handlers = value.handlers
c.Params = value.params
c.fullPath = value.fullPath
c.Next() // 执行函数链条
c.writermem.WriteHeaderNow()
return
}
// liwenzhou.com...
c.handlers = engine.allNoRoute
serveError(c, http.StatusNotFound, default404Body)
}
在该函数中,注意c.Next()
。也就是在浏览器发出请求后,gin会根据请求方法在路由树中找到对应的节点(通过root.getValue
函数),然后通过c.Next()
执行该节点的handlers。这里的c.Next()
是第一个被调用的c.Next()。之后的每个中间件都会调用一次c.Next()
下面是c.Next()
的代码
func (c *Context) Next() {
c.index++
for c.index < int8(len(c.handlers)) {
c.handlers[c.index](c)
c.index++
}
}
其中,c.index
初始值为-1.所以,第一次调用Next,先将index加到0,然后进入循环,执行了注册的中间件m1,在m1中又调用了Next,再进到Next中,此时的index++后等于1,进入循环,执行c.handlers[1](c),也就是m2。m2 中继续调用next,重复上述操作,最终index==len(c.handlers)-1,执行了最后一个handler,也就是最后注册的请求处理函数。index再加一,退出循环,退出Next函数,就回到了m3.m3再执行完,退出到m2调用的Next中,此时index已经等于len(c.handlers)了,所以循环直接退出,也就退出了m2。同样,退出m2执行流来到m1调用的Next中,再退出。可以看出,是一个嵌套的调用。