入门gin
特性
- 基于radix树,无反射,小内存占用
- 支持中间件
- crash处理:gin可以捕捉panic并recover,保持服务器始终可用
数据结构
- Context Pool
- RouterGroup:储存路由组及中间件
- methodTrees:http方法对应的路由树(采用的是radix树,原型为trie树)
- 交互流程:gin.Default()获得engine实例并启用中间件,创建路由树和context池,然后启动http监听端口
核心概念
Engine
- 框架实例,包含中间件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25type Engine struct {
RouterGroup // 路由组
RemoteIPHeaders []string
HTMLRender render.HTMLRender
FuncMap template.FuncMap // 自定义函数
pool sync.Pool // gin.Context 缓存池
trees methodTrees // 不同 HTTP 方法的路由树
}
// 常用方法
// Default 包含默认的 Logger 和 Recovery 中间件
func Default() *Engine
// New 无中间件
func New() *Engine
// Run 监听端口并启动HTTP服务
func (engine *Engine) Run(addr ...string) (err error)
// Routes 获取已绑定的routes
func (engine *Engine) Routes() (routes RoutesInfo)
// Use 绑定中间件
func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes
HandlerFunc
- 返回中间件
1
2
3
4
5
6
7
8
9
10
11
12
13
14type HandlerFunc func(*Context)
// BasicAuth 基础的 HTTP 验证
func BasicAuth(accounts Accounts) HandlerFunc
// Bind 根据参数返回中间件
func Bind(val any) HandlerFunc
// Logger 打印日志
func Logger() HandlerFunc
// CustomRecovery 从 panic 中恢复
func Recovery() HandlerFunc
func CustomRecovery(handle RecoveryFunc) HandlerFunc
Router
- 路由定义
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19type IRoutes interface {
Use(...HandlerFunc) IRoutes
Handle(string, string, ...HandlerFunc) IRoutes
Any(string, ...HandlerFunc) IRoutes
GET(string, ...HandlerFunc) IRoutes
POST(string, ...HandlerFunc) IRoutes
DELETE(string, ...HandlerFunc) IRoutes
PATCH(string, ...HandlerFunc) IRoutes
PUT(string, ...HandlerFunc) IRoutes
OPTIONS(string, ...HandlerFunc) IRoutes
HEAD(string, ...HandlerFunc) IRoutes
Match([]string, string, ...HandlerFunc) IRoutes
StaticFile(string, string) IRoutes
StaticFileFS(string, string, http.FileSystem) IRoutes
Static(string, string) IRoutes
StaticFS(string, http.FileSystem) IRoutes
} - RouterInfo
1
2
3
4
5
6type RouteInfo struct {
Method string
Path string
Handler string
HandlerFunc HandlerFunc
}
Trie
- 前缀树,字典树,用于路由树设计
- Radix tree:压缩前缀树,将只有一个子节点的中间节点压缩,时间效率为O(K)
简易实现:gee
参考:huanglianjing的博客
cover:
画师:chicken_ash
id:121457140
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 suisbuds!