r.Run(":8080")func(engine*Engine)Run(addr...string)(errerror){// 参数是监听地址
deferfunc(){debugPrintError(err)}()address:=resolveAddress(addr)debugPrint("Listening and serving HTTP on %s\n",address)err=http.ListenAndServe(address,engine)// 重点在这里
return}
func(engine*Engine)handleHTTPRequest(c*Context){// ...
// Find root of the tree for the given HTTP method
t:=engine.treesfori,tl:=0,len(t);i<tl;i++{ift[i].method!=httpMethod{continue}root:=t[i].root// Find route in tree
// getValue 返回给定路径上注册的handle 路由匹配算法在这个函数实现
value:=root.getValue(rPath,c.Params,unescape)ifvalue.handlers!=nil{c.handlers=value.handlersc.Params=value.paramsc.fullPath=value.fullPathc.Next()// 注意这个函数一般只在中间件中调用,依次调用注册的函数
c.writermem.WriteHeaderNow()return}// 没匹配到路由的处理 ...
// ...
}
// 这个函数把用户注册的handle和中间件的handle组合起来并返回
func(group*RouterGroup)combineHandlers(handlersHandlersChain)HandlersChain{finalSize:=len(group.Handlers)+len(handlers)iffinalSize>=int(abortIndex){panic("too many handlers")}mergedHandlers:=make(HandlersChain,finalSize)copy(mergedHandlers,group.Handlers)copy(mergedHandlers[len(group.Handlers):],handlers)returnmergedHandlers}
func(engine*Engine)Run(addr...string)(errerror){// ...
err=http.ListenAndServe(address,engine)return}// Engine实现了http.Handler接口,当请求过来时,会调用如下函数
func(engine*Engine)ServeHTTP(whttp.ResponseWriter,req*http.Request){c:=engine.pool.Get().(*Context)c.writermem.reset(w)c.Request=reqc.reset()engine.handleHTTPRequest(c)engine.pool.Put(c)}func(engine*Engine)handleHTTPRequest(c*Context){// ...
// Find root of the tree for the given HTTP method
t:=engine.treesfori,tl:=0,len(t);i<tl;i++{ift[i].method!=httpMethod{continue}root:=t[i].root// Find route in tree
value:=root.getValue(rPath,c.Params,unescape)// 拿到路由上注册的函数
ifvalue.handlers!=nil{c.handlers=value.handlersc.Params=value.paramsc.fullPath=value.fullPathc.Next()// 调用所有
c.writermem.WriteHeaderNow()return}// ...
}