一、gin的路由算法
註冊路由預處理
我們在使用gin時通過下面的代碼註冊路由
普通註冊
router.POST("/login", func(context *gin.Context) {
context.String(http.StatusOK, "login")
})
使用中間件
router.Use(Logger())
使用Group
v1 := router.Group("v1"){
v1.GET("/product/detail", func(context *gin.Context) {
context.String(http.StatusOK, "product")
})
}
這些操作, 最終都會在反應到gin的路由樹上
具體實現
比如 POST(“/login”)
// routergroup.go:L72-77
func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {
absolutePath := group.calculateAbsolutePath(relativePath)
// relativePath<---/login
handlers = group.combineHandlers(handlers)
group.engine.addRoute(httpMethod, absolutePath, handlers)
return group.returnObj()
}
在調用POST, GET, HEAD等路由HTTP相關函數時, 會調用handle函數
如果調用了中間件的話, 會調用下面函數
func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {
group.Handlers = append(group.Handlers, middleware...)
return group.returnObj()
}
如果使用了Group的話, 會調用下面函數
func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {
return &RouterGroup{
Handlers: group.combineHandlers(handlers),
basePath: group.calculateAbsolutePath(relativePath),
engine: group.engine,
}
}
重點關注下面兩個函數:
// routergroup.go:L208-217
func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {
finalSize := len(group.Handlers) + len(handlers)
if finalSize >= int(abortIndex) {
panic("too many handlers")
}
mergedHandlers := make(HandlersChain, finalSize)
copy(mergedHandlers, group.Handlers)
copy(mergedHandlers[len(group.Handlers):], handlers)
return mergedHandlers
}
func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {
return joinPaths(group.basePath, relativePath)
}
func joinPaths(absolutePath, relativePath string) string {
if relativePath == "" {
return absolutePath
}
finalPath := path.Join(absolutePath, relativePath)
appendSlash := lastChar(relativePath) == '/' && lastChar(finalPath) != '/'
if appendSlash {
return finalPath + "/"
}
return finalPath
}
在joinPaths函數
func joinPaths(absolutePath, relativePath string) string {
if relativePath == "" {
return absolutePath
}
finalPath := path.Join(absolutePath, relativePath)
appendSlash := lastChar(relativePath) == '/' && lastChar(finalPath) != '/'
if appendSlash {
return finalPath + "/"
}
return finalPath
}
在當路由是/user/這種情況就滿足了lastChar(relativePath) == '/' && lastChar(finalPath) != '/'. 主要原因是path.Join(absolutePath, relativePath)之後, finalPath是/user
綜合來看, 在預處理階段
- 在調用中間件的時候, 是將某個路由的handler處理函數和中間件的處理函數都放在了Handlers的數組中
- 在調用Group的時候, 是將路由的path上面拼上Group的值. 也就是/product/detail, 會變成v1/product/detail
真正註冊
// routergroup.go:L72-77
func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {
absolutePath := group.calculateAbsolutePath(relativePath) // <---
handlers = group.combineHandlers(handlers) // <---
group.engine.addRoute(httpMethod, absolutePath, handlers)
return group.returnObj()
}
調用group.engine.addRoute(httpMethod, absolutePath, handlers)將預處理階段的結果註冊到gin Engine的trees上
gin路由樹簡單介紹
gin的路由樹算法是一棵前綴樹. 不過並不是只有一顆樹, 而是每種方法(POST, GET, ...)都有自己的一顆樹
func (engine *Engine) addRoute(method, path string, handlers HandlersChain) {
assert1(path[0] == '/', "path must begin with '/'")
assert1(method != "", "HTTP method can not be empty")
assert1(len(handlers) > 0, "there must be at least one handler")
debugPrintRoute(method, path, handlers)
root := engine.trees.get(method) // <-- 看這裏
if root == nil {
root = new(node)
engine.trees = append(engine.trees, methodTree{method: method, root: root})
}
root.addRoute(path, handlers)
}
gin 路由最終的樣子大概是下面的樣子
// tree.go:88
type node struct {
// 相對路徑
path string
// 索引
indices string
// 子節點
children []*node
// 處理者列表
handlers HandlersChain
priority uint32
// 結點類型:static, root, param, catchAll
nType nodeType
// 最多的參數個數
maxParams uint8
// 是否是通配符(:param_name | *param_name)
wildChild bool
}
其實gin的實現不像一個真正的樹, children []*node所有的孩子都放在這個數組裏面, 利用indices, priority變相實現一棵樹
獲取路由handler
當服務端收到客戶端的請求時, 根據path去trees匹配到相關的路由, 拿到相關的處理handlers
// gin.go : 368行
t := engine.trees
for i, tl := 0, len(t); i < tl; i++ {
if t[i].method != httpMethod {
continue
}
root := t[i].root
// Find route in tree
handlers, params, tsr := root.getValue(path, c.Params, unescape)
if handlers != nil {
c.handlers = handlers
c.Params = params
c.Next()
c.writermem.WriteHeaderNow()
return
}
if httpMethod != "CONNECT" && path != "/" {
if tsr && engine.RedirectTrailingSlash {
redirectTrailingSlash(c)
return
}
if engine.RedirectFixedPath && redirectFixedPath(c, root, engine.RedirectFixedPath) {
return
}
}
break
}
...
主要在下面這個函數裏面調用程序註冊的路由處理函數
func (c *Context) Next() {
c.index++
for c.index < int8(len(c.handlers)) {
c.handlers[c.index](c)
c.index++
}
}
二、總結
gin的是路由算法其實就是一個Trie樹(也就是前綴樹),router使用的數據結構被稱爲壓縮字典樹(Radix Tree)
三、參考
1.https://chai2010.cn/advanced-go-programming-book/ch5-web/ch5-02-router.html
2.https://www.kancloud.cn/liuqing_will/the_source_code_analysis_of_gin/616924
3.https://www.jianshu.com/p/5c0f1925f5db