当前位置: 首页 > news >正文

Gin源码解析

结构

Engine
RouterGroup
HandlersChain
Context

Engine的结构为

typeEnginestruct{RouterGroup routeTreesUpdated sync.Once RedirectTrailingSlashboolRedirectFixedPathboolHandleMethodNotAllowedboolForwardedByClientIPboolAppEngineboolUseRawPathboolUseEscapedPathboolUnescapePathValuesboolRemoveExtraSlashboolRemoteIPHeaders[]stringTrustedPlatformstringMaxMultipartMemoryint64UseH2CboolContextWithFallbackbooldelims render.Delims secureJSONPrefixstringHTMLRender render.HTMLRender FuncMap template.FuncMap allNoRoute HandlersChain allNoMethod HandlersChain noRoute HandlersChain noMethod HandlersChain pool sync.Pool trees methodTrees maxParamsuint16maxSectionsuint16trustedProxies[]stringtrustedCIDRs[]*net.IPNet}

allNoRoute:没有找到路由时的处理链
allNoMethod:方法没有找到时的处理链
RouterGroup结构为

typeRouterGroupstruct{Handlers HandlersChain basePathstringengine*Engine rootbool}

HandlersChain为函数切片

typeHandlerFuncfunc(*Context)typeHandlersChain[]HandlerFunc

Context为处理中的关键数据结构

typeContextstruct{writermem responseWriter Request*http.Request Writer ResponseWriter Params Params handlers HandlersChain indexint8fullPathstringengine*Engine params*Params skippedNodes*[]skippedNode// This mutex protects Keys map.mu sync.RWMutex// Keys is a key/value pair exclusively for the context of each request.Keysmap[any]any// Errors is a list of errors attached to all the handlers/middlewares who used this context.Errors errorMsgs// Accepted defines a list of manually accepted formats for content negotiation.Accepted[]string// queryCache caches the query result from c.Request.URL.Query().queryCache url.Values// formCache caches c.Request.PostForm, which contains the parsed form data from POST, PATCH,// or PUT body parameters.formCache url.Values// SameSite allows a server to define a cookie attribute making it impossible for// the browser to send this cookie along with cross-site requests.sameSite http.SameSite}

创建

创建Engine是通过Default方法

  • 先使用New()创建Engine
  • 使用OptionFunc函数来配置Engine
funcDefault(opts...OptionFunc)*Engine{debugPrintWARNINGDefault()engine:=New()engine.Use(Logger(),Recovery())returnengine.With(opts...)}funcNew(opts...OptionFunc)*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"},TrustedPlatform:defaultPlatform,UseRawPath:false,UseEscapedPath:false,RemoveExtraSlash:false,UnescapePathValues:true,MaxMultipartMemory:defaultMultipartMemory,trees:make(methodTrees,0,9),delims:render.Delims{Left:"{{",Right:"}}"},secureJSONPrefix:"while(1);",trustedProxies:[]string{"0.0.0.0/0","::/0"},trustedCIDRs:defaultTrustedCIDRs,}engine.engine=engine engine.pool.New=func()any{returnengine.allocateContext(engine.maxParams)}returnengine.With(opts...)}func(engine*Engine)With(opts...OptionFunc)*Engine{for_,opt:=rangeopts{opt(engine)}returnengine}

OptionFunc为函数别名

typeOptionFuncfunc(*Engine)

运行

是通过Run来执行

  • 在没有指定地址信息时,读取环境变量PORT端口号,没有则默认使用端口号8080
  • 内部创建http.Server,handler为engine.Handler(),执行http.Server的方法ListenAndServe,其中Engine是实现了http.Handler接口
func(engine*Engine)Run(addr...string)(errerror){deferfunc(){debugPrintError(err)}()ifengine.isUnsafeTrustedProxies(){debugPrint("[WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value.\n"+"Please check https://github.com/gin-gonic/gin/blob/master/docs/doc.md#dont-trust-all-proxies for details.")}engine.updateRouteTrees()address:=resolveAddress(addr)debugPrint("Listening and serving HTTP on %s\n",address)server:=&http.Server{// #nosec G112Addr:address,Handler:engine.Handler(),}err=server.ListenAndServe()return}

Engine实现了http.Handler接口方法ServeHTTP,内部调用handleHTTPRequest,根据请求方法和请求url,找到对应的HandlersChain,执行Context的Next()方法,遍历处理链执行处理

func(engine*Engine)ServeHTTP(w http.ResponseWriter,req*http.Request){engine.routeTreesUpdated.Do(func(){engine.updateRouteTrees()})c:=engine.pool.Get().(*Context)c.writermem.reset(w)c.Request=req c.reset()engine.handleHTTPRequest(c)engine.pool.Put(c)}func(engine*Engine)handleHTTPRequest(c*Context){httpMethod:=c.Request.Method rPath:=c.Request.URL.Path unescape:=falseifengine.UseEscapedPath{rPath=c.Request.URL.EscapedPath()unescape=engine.UnescapePathValues}elseifengine.UseRawPath&&len(c.Request.URL.RawPath)>0{rPath=c.Request.URL.RawPath unescape=engine.UnescapePathValues}ifengine.RemoveExtraSlash{rPath=cleanPath(rPath)}// Find root of the tree for the given HTTP methodt:=engine.treesfori,tl:=0,len(t);i<tl;i++{ift[i].method!=httpMethod{continue}root:=t[i].root// Find route in treevalue:=root.getValue(rPath,c.params,c.skippedNodes,unescape)ifvalue.params!=nil{c.Params=*value.params}ifvalue.handlers!=nil{c.handlers=value.handlers c.fullPath=value.fullPath c.Next()c.writermem.WriteHeaderNow()return}ifhttpMethod!=http.MethodConnect&&rPath!="/"{ifvalue.tsr&&engine.RedirectTrailingSlash{redirectTrailingSlash(c)return}ifengine.RedirectFixedPath&&redirectFixedPath(c,root,engine.RedirectFixedPath){return}}break}ifengine.HandleMethodNotAllowed&&len(t)>0{// According to RFC 7231 section 6.5.5, MUST generate an Allow header field in response// containing a list of the target resource's currently supported methods.allowed:=make([]string,0,len(t)-1)for_,tree:=rangeengine.trees{iftree.method==httpMethod{continue}ifvalue:=tree.root.getValue(rPath,nil,c.skippedNodes,unescape);value.handlers!=nil{allowed=append(allowed,tree.method)}}iflen(allowed)>0{c.handlers=engine.allNoMethod c.writermem.Header().Set("Allow",strings.Join(allowed,", "))serveError(c,http.StatusMethodNotAllowed,default405Body)return}}c.handlers=engine.allNoRouteserveError(c,http.StatusNotFound,default404Body)}func(c*Context)Next(){c.index++forc.index<safeInt8(len(c.handlers)){ifc.handlers[c.index]!=nil{c.handlers[c.index](c)}c.index++}}
http://www.cnnetsun.cn/news/51116.html

相关文章:

  • 冒泡排序 ~ 背下来的 哭
  • 手把手教你学Simulink——机器人轨迹跟踪场景实例:基于Simulink的永磁同步电机关节空间直线轨迹跟踪控制仿真
  • 盈富宝典 通达信主图
  • 14、Python在不同场景下的应用与实践
  • X-AnyLabeling 自动数据标注保姆级教程:从安装到格式转换全流程
  • 38、深入探索bc计算器、数组及特殊编程技巧
  • vue基于Spring Boot框架的技术实现的医院住院管理系统_229p8ejv
  • 基于vue的停车场预约管理系统地图_n7nz82g6_springboot php python nodejs
  • 基于vue的宠物领养系统的设计与实现_389i5918_springboot php python nodejs
  • 基于vue的生鲜团购管理系统设计与实现优惠卷_2av6282k_springboot php python nodejs
  • React Native桌面应用交互终极指南:从点击事件到原生菜单完整教程
  • Springboot美食分享网站a73c9(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
  • Springboot门店运营管理系统hd158(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
  • Stellarium望远镜控制实战指南:从硬件连接到精准观测
  • 快速验证:基于CentOS 7.6的测试环境搭建
  • AI定价实战指南:快速构建电商智能定价系统
  • VGGT三维重建终极指南:从零开始构建你的3D世界
  • 电商网站秒开秘籍:快马AI加载优化案例
  • 15分钟快速验证:谷歌服务离线包生成器原型开发
  • 1小时搞定ElementUI原型:快马平台实战
  • 从天喵装机案例看中小企业IT设备采购新范式
  • Flink面试题实战:从问题到解决方案
  • 5分钟用C# Socket搭建文件传输原型
  • 论文查重不花一分钱?宏智树AI开启学术诚信新“净”界!
  • 最强安卓投屏神器QtScrcpy
  • 开题报告“自造机”VS“人工苦力”:宏智树AI凭何成为学术起航新引擎?
  • 还在为SPSS代码头疼?5款AI数据分析工具实测:有的只能画图,有的却能直接嵌入论文全流程
  • 单环PID控制Buck电路实现方案
  • 零基础必学:CSS div居中完全指南(图文详解)
  • COCO数据集工具库完整使用指南:从入门到实战应用