gin框架作爲Golang的輕量級web框架,包含了路由的dispatch功能,本文將重點分析根據設置的請求path構建路由前綴樹的相關功能。本文分析是基於gin 1.6.3版本的代碼實現。
1. 路由存儲的結構和算法
Engine是gin框架的實例,在Engine結構中,trees 是一個數組,針對框架支持的每一種方法,都會創建一個節點。例如GET、POST是trees的兩個元素。
//框架實例包含一個方法數數組
type Engine struct {
trees methodTrees
}
type methodTrees []methodTree
//方法樹的定義
type methodTree struct {
method string
root *node
}
1.1 前綴樹節點的定義
//path樹的節點結構
type node struct {
path string
indices string
children []*node
handlers HandlersChain
priority uint32
nType nodeType
maxParams uint8
wildChild bool
fullPath string
}
方法樹是通過節點包含children的節點數組的結構形成的,在node結構中:
path:表示當前節點的path;
indices:通常情況下維護了children列表的path的各首字符組成的string,之所以是通常情況,是在處理包含通配符的path處理中會有一些例外情況;
priority:代表了有幾條路由會經過此節點,用於在節點進行排序時使用;
nType:是節點的類型,默認是static類型,還包括了root類型,對於path包含冒號通配符的情況,nType是 param類型,對於包含 * 通配符的情況,nType類型是 catchAll 類型;
wildChild:默認是false,當children是 通配符類型時,wildChild爲true;
原文鏈接:【https://www.infoq.cn/article/8Tg1alapeyfcAKF6zwGh】。未經作者許可,禁止轉載。