1、笔记、结论:
1.1 简介
Gin 是一个用 Go (Golang) 编写的 Web 框架。它具有类似martini-like的 API,由于 httprouter,性能提高了 40 倍。如果您需要性能和良好的生产力,您会喜欢 Gin。
1.2 tips:
1、各个router以树状存储,并GET/POST/PUT等为各个根结点
2、请求进来时,匹配上后,执行对应handlers
3、树的分叉处以路径的不同分开
4、各个节点indices为子节点的首字母,路径经历得多的,排在前面
5、实现了http的serveHTTP,才能讲context传入传出http服务
2、重要的结构体:
2.1 gin.go
2.1.1 Engine
engine是框架的实例,它包含了锁、中间件和配置生成
type Engine struct {
RouterGroup
// 以下为属性配置
RedirectTrailingSlash bool
RedirectFixedPath bool
HandleMethodNotAllowed bool
ForwardedByClientIP bool
AppEngine bool
UseRawPath bool
UnescapePathValues bool
RemoveExtraSlash bool
RemoteIPHeaders []string
TrustedProxies []string
TrustedPlatform string
MaxMultipartMemory int64
// 以下为一些重要的常用类型
delims render.Delims
secureJSONPrefix string
HTMLRender render.HTMLRender
FuncMap template.FuncMap
allNoRoute HandlersChain
allNoMethod HandlersChain
noRoute HandlersChain
noMethod HandlersChain
pool sync.Pool
trees methodTrees
maxParams uint16
trustedCIDRs []*net.IPNet
}
2.1.2 RouterGroup
routerGroup在内部用于配制路由,并与路由前缀、处理中间件函数相关联。
type RouterGroup struct {
Handlers HandlersChain
basePath string
engine *Engine
root bool
}
2.1.3 HandlersChain、HandlerFunc
// HandlerFunc defines the handler used by gin middleware as return value.
type HandlerFunc func(*Context)
// HandlersChain defines a HandlerFunc array.
type HandlersChain []HandlerFunc
2.2 tree.go
2.2.1 methodTree
type methodTree struct {
method string
root *node
}
2.2.2 node
method树结构中的节点
type node struct {
path string
indices string // childNode的首字符,用于路由时匹配
wildChild bool
nType nodeType
priority uint32 // 优先级,也是当前节点被引用次数。父节点indices根据此pri进行排序
children []*node // child nodes, at most 1 :param style node at the end of the array
handlers HandlersChain
fullPath string
}
3、函数:
3.1 gin.go
3.1.1 New():
初始化engine,RouterGroup的engine。engine.pool.new指定分配context函数
func New() *Engine {
debugPrintWARNINGNew()
engine := &Engine{
RouterGroup: RouterGroup{
Handlers: nil,
basePath: "/",
root: true,
},
FuncMap: template.FuncMap{
},
RedirectTrailingSlash: true,
RedirectFixedPath: false,
HandleMethodNotAllowed: false,
ForwardedByClientIP: true,
RemoteIPHeaders: []string{
"X-Forwarded-For", "X-Real-IP"},
TrustedProxies: []string{
"0.0.0.0/0"},
TrustedPlatform: defaultPlatform,
UseRawPath: false,
RemoveExtraSlash: false,
UnescapePathValues: true,
MaxMultipartMemory: defaultMultipartMemory,
trees: make(methodTrees, 0, 9),
delims: render.Delims{
Left: "{
{", Right: "}}"},
secureJSONPrefix: