One minute
Gin
gin是一个广泛使用的、golang风格的http框架, github地址: gin
Engine
在gin的实现中. Engine是整个核心, 定义如下
type Engine struct {
RouterGroup
FuncMap template.FuncMap
allNoRoute HandlersChain
allNoMethod HandlersChain
noRoute HandlersChain
noMethod HandlersChain
pool sync.Pool
trees methodTrees
Engin实现了golang的http接口, 接口和启动方法的查看如下
// ServeHTTP conforms to the http.Handler interface.
func (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
c := engine.pool.Get().(*Context)
c.writermem.reset(w)
c.Request = req
c.reset()
engine.handleHTTPRequest(c)
engine.pool.Put(c)
}
func (engine *Engine) Run(addr ...string) (err error) {
defer func() { debugPrintError(err) }()
address := resolveAddress(addr)
debugPrint("Listening and serving HTTP on %s\n", address)
err = http.ListenAndServe(address, engine)
return
}
Engine隐式继承了RouterGroup, RouterGroup 提供了方法和middleware的注册, 每次注册方法的时候, 会进行merge middleware生成新的 HandlersChain, 并挂载到 响应方法的树上(本质上是一个前缀树).
gin前缀树的实现原理参考: https://segmentfault.com/a/1190000016655709
94 Words
2019-06-16 10:12 +0800