gin源码分析(1)--初始化中间件,路由组与路由树

目标

  1. 关于gin.Default(),gin.New(),gin.Use()
  2. group与子group之间的关系,多group与middleware之间关系
  3. 中间件的类型,全局,group,get,不同类型的中间件什么时候执行。中间件 next 和abort行为
  4. 如何实现http请示请求?http并发如何处理,middleware的context是什么

基本用法

func initMiddleware(ctx *gin.Context) {fmt.Println("全局中间件 通过 r.Use 配置")// 调用该请求的剩余处理程序ctx.Next()// 终止调用该请求的剩余处理程序//ctx.Abort()
}//0. 初始化
r := gin.Default()//1. 全局中间件
r.Use(initMiddleware)//2. group与子group,类型为RouterGroup
adminRouter := router.Group("/admin", initMiddleware)
userRouter  := adminRouters.Group("/user", initMiddleware)//3. 请求
userRouters.GET("/user", initMiddleware, controller.UserController{}.Index)//4. 中间件共享数据
ctx.Set("username", "张三")
username, _ := ctx.Get("username")

关于初始化

使用流程中涉及到几个重要的结构体

gin.Engine,gin.Context,gin.RouterGroup

gin.Default(),gin.New(),gin.Use()
func Default() *Engine {// 初始化一个新的Egineengine := New()// 默认注册全局中间件Logger()和Recovery()//Logger()定义一个中间件,实现每次请求进来的日志打印//可以配置日志的过滤路径,打印颜色,打印的位置等 //Recovery()定义一个中间件,用来拦截运行中产生的所有panic,输出打印并返回500//同样可以配置全局panic拦截的行为//如果要配置Logger与Recovery则直接在应用中使用gin.New()。然后再在应用中调用//engine.Use(LoggerWithFormatter(xxxx), RecoveryWithWriter(xxxx))。engine.Use(Logger(), Recovery())return engine
}//初始化Engine
func New() *Engine {engine := &Engine{//初始化化第一个RouterGroup, root表示是否为根RouterGroupRouterGroup: RouterGroup{Handlers: nil,basePath: "/",root:     true,},FuncMap:                template.FuncMap{},TrustedPlatform:        defaultPlatform,MaxMultipartMemory:     defaultMultipartMemory,//请求方法数组,GET,POST,DELETE,每个方法下面有个链表trees:                  make(methodTrees, 0, 9),delims:                 render.Delims{Left: "{{", Right: "}}"},//已删除部分配置项}//给第一个Group配置engine,也就是本engineengine.RouterGroup.engine = engineengine.pool.New = func() any {return engine.allocateContext(engine.maxParams)}return engine
}//注册全局中间件
func (engine *Engine) Use(middleware ...HandlerFunc) IRoutes {//把middleware函数append到上面创建的engine的根RouterGroup的Handlers数组中 engine.RouterGroup.Use(middleware...)//初始化404和405处理的中间间engine.rebuild404Handlers()engine.rebuild405Handlers()return engine
}

Engine继承了RouterGroup,gin.Default()初始化了Engine与第一个RouterGroup,并初始化了两个默认的中间件,Logger(), Recovery(),他们的作用与配置上面代码中有介绍

gin.Use的核心功能为把传入进来的中间件合并到RouterGroup的Handlers数组中,代码如下

group.Handlers = append(group.Handlers, middleware...)
重要的结构体
type HandlerFunc func(*Context)
type HandlersChain []HandlerFunctype RouterGroup struct {Handlers HandlersChainbasePath stringengine   *Engineroot     bool
}type RoutesInfo []RouteInfotype Engine struct {//继承RouterGroupRouterGroup//此处已省略部分gin的请求配置的字段,//gin的很多请求配置都在这,需要了解的可以看一下注释或官方文档delims           render.DelimsHTMLRender       render.HTMLRenderFuncMap          template.FuncMap//所有的404的回调中间件allNoRoute       HandlersChain//所有的405请求类型没对上的回调中间件,使用gin.NoMethod设置allNoMethod      HandlersChain//404的回调中间件,使用gin.NoRoute设置,会合并到allNoRoute中noRoute          HandlersChain//同上noMethod         HandlersChainpool             sync.Pooltrees            methodTrees
}

创建Group

Engine继承RouterGroup,RouterGroup里又有一个engine变量

之前猜测,RouterGroup与RouterGroup之前通过链表连接起来,目前来看上一个RouterGroup与当前RouterGroup没什么连接关系

只是利用上一个RouterGroup的Group函数创建一个新的RouterGroup,并把之前RouterGroup与Engine注册的中间件全部复制过来

//用法:adminRouters := r.Group("/admin", middlewares.InitMiddleware)//参数relativePath:RouterGroup的路径
//参数handlers:处理函数
func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {//创建一个新的RouterGroupreturn &RouterGroup{//把上一个Router的中间件,全局中间件与新中间件函数合并到新RouterHandlers: group.combineHandlers(handlers),//把上一个Router的路径与新的Router路径相加得到新的地址basePath: group.calculateAbsolutePath(relativePath),engine:   group.engine,}
}

创建Get请求

//使用方法userRouters.GET("/user", middlewares.InitMiddleware, controller.UserController{}.Index)
func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {return group.handle(http.MethodGet, relativePath, handlers)
}func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {absolutePath := group.calculateAbsolutePath(relativePath)//这里有疑问,为什么要把GET请示所有的执行函数加入到group的handlers里handlers = group.combineHandlers(handlers)//把请求加入到方法树中group.engine.addRoute(httpMethod, absolutePath, handlers)return group.returnObj()
}type node struct {path      stringindices   stringwildChild boolnType     nodeTypepriority  uint32children  []*node // child nodes, at most 1 :param style node at the end of the arrayhandlers  HandlersChainfullPath  string
}type methodTree struct {method stringroot   *node
}type methodTrees []methodTreefunc (engine *Engine) addRoute(method, path string, handlers HandlersChain) {//engine.trees,是一个methodTrees的切片//trees.get()找到哪一个属于GET请求的树,找不到则new一个root := engine.trees.get(method)if root == nil {root = new(node)root.fullPath = "/"engine.trees = append(engine.trees, methodTree{method: method, root: root})}//插入router的请求树中root.addRoute(path, handlers)//删除部分参数初始化}

插入请求树

//第一个路径/list
//第二个路径/list2
//第三个路径/licq
//第四个路径/li:id 
func (n *node) addRoute(path string, handlers HandlersChain) {fullPath := pathn.priority++//插入第一个路径时,root node为空,直接插入 if len(n.path) == 0 && len(n.children) == 0 {//insertChild做两件事//1. 解析参数,并插入参数节点 //2. 直接参数节点,第一个路径节点就简单地插入到GET的tree中 //到此/list结点添加完成,type=1, childrenLen=0, priority:1, indices:无 n.insertChild(path, fullPath, handlers)n.nType = rootreturn}parentFullPathIndex := 0walk:for {// Find the longest common prefix.// This also implies that the common prefix contains no ':' or '*'// since the existing key can't contain those chars.//找出新插入路径path与上一个插入的节点的路径做比较,找出连续相同字符的数量 //  /xxx/list与/xxx/list2,前9个字符相同,所以i等于9 i := longestCommonPrefix(path, n.path)// Split edge// 添加list2:list2的i == len(n.path)相同,不走这里 // 添加licq: 走这里,且整棵树下移 if i < len(n.path) {child := node{path:      n.path[i:],wildChild: n.wildChild,nType:     static,indices:   n.indices,children:  n.children,handlers:  n.handlers,priority:  n.priority - 1,fullPath:  n.fullPath,}//整棵树下移 n.children = []*node{&child}// []byte for proper unicode char conversion, see #65n.indices = bytesconv.BytesToString([]byte{n.path[i]})//第一次添加list,第一个节点为的path为list//第二次添加list2,因为与父节点节点前面相同,则父节点path为list,节点path为2//第三次添加licq,新节点与list节点前面li相同,//所以把父节点改为li,原来的list改为st, cq节点与st结点同为li的子节点,//最终结构如下//   |->cq//li |//   |->st-->2//修改原来的父节点 n.path = path[:i]n.handlers = niln.wildChild = falsen.fullPath = fullPath[:parentFullPathIndex+i]}//  添加list2:list2的i < len(path)走这里 // Make new node a child of this nodeif i < len(path) {//截取list2中的2,path==[2]path = path[i:]c := path[0]// '/' after param// 添加list2:n为上个list的node的nType为root,不走这里 if n.nType == param && c == '/' && len(n.children) == 1 {parentFullPathIndex += len(n.path)n = n.children[0]n.priority++continue walk}// Check if a child with the next path byte exists// 如果父节点有indices,且与c相同,则找下一个节点 for i, max := 0, len(n.indices); i < max; i++ {if c == n.indices[i] {parentFullPathIndex += len(n.path)i = n.incrementChildPrio(i)n = n.children[i]continue walk}}// Otherwise insert itif c != ':' && c != '*' && n.nType != catchAll {//  添加list2:list的node的indices为2 // []byte for proper unicode char conversion, see #65n.indices += bytesconv.BytesToString([]byte{c})//  添加list2:创建list2的node child := &node{fullPath: fullPath,}//  添加list2:把list2的node插入到list的node children中 n.addChild(child)//  添加list2:设置priority,并把高priority的chdil排在前面n.incrementChildPrio(len(n.indices) - 1)// 这里把n切换为child,做后面的设置n = child} else if n.wildChild {// inserting a wildcard node, need to check if it conflicts with the existing wildcardn = n.children[len(n.children)-1]n.priority++// Check if the wildcard matchesif len(path) >= len(n.path) && n.path == path[:len(n.path)] &&// Adding a child to a catchAll is not possiblen.nType != catchAll &&// Check for longer wildcard, e.g. :name and :names(len(n.path) >= len(path) || path[len(n.path)] == '/') {continue walk}// Wildcard conflictpathSeg := pathif n.nType != catchAll {pathSeg = strings.SplitN(pathSeg, "/", 2)[0]}prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.pathpanic("'" + pathSeg +"' in new path '" + fullPath +"' conflicts with existing wildcard '" + n.path +"' in existing prefix '" + prefix +"'")}//如上所述,如果路径没有参数,此函数的作用为n.handlers = handlersn.insertChild(path, fullPath, handlers)return}// Otherwise add handle to current nodeif n.handlers != nil {panic("handlers are already registered for path '" + fullPath + "'")}n.handlers = handlersn.fullPath = fullPathreturn}
}

路由树图示

下面通过图示来看一下,每次增加一个请求,路由树会有什么变化。

如果插入一个带参数的请求如/list/:id/:sn,流程和上面代码所分析的基本一至,只是会在/list挂两个param结点,id与sn

userRouters.GET("/list", Index)
userRouters.GET("/list2", Index)
userRouters.GET("/list23", Index)

userRouters.GET("/list33", Index)
userRouters.GET("/liicq", Index)

测试代码

自己写了一个代码去打印树结构

func _p(level int, pre string, n *node){for i := 0; i < level+1; i++ {fmt.Print(pre)}fmt.Printf(" path=%v, type=%d, childrenLen=%d, priority:%d, indices:%s, wildChild=%t\n",n.path, n.nType, len(n.children), n.priority, n.indices, n.wildChild)
}func (group *RouterGroup) printNode(level int, node *node) {if len(node.children) != 0 || level == 0 {_p(level, "#", node)}if len(node.children) != 0 {for _, n := range node.children {_p(level, "-", n)}level++for _, n := range node.children {group.printNode(level, n);}}
}

打印结果

//测试内容
userRouters.GET("/list", Index)
userRouters.GET("/list2", Index)
userRouters.GET("/list23", Index)
userRouters.GET("/list33", Index)
userRouters.GET("/liicq", Index)//打印结果
# path=/admin/user/li, type=1, childrenLen=2, priority:5, indices:si, wildChild=false
- path=st, type=0, childrenLen=2, priority:4, indices:23, wildChild=false
- path=icq, type=0, childrenLen=0, priority:1, indices:, wildChild=false
## path=st, type=0, childrenLen=2, priority:4, indices:23, wildChild=false
-- path=2, type=0, childrenLen=1, priority:2, indices:3, wildChild=false
-- path=33, type=0, childrenLen=0, priority:1, indices:, wildChild=false
### path=2, type=0, childrenLen=1, priority:2, indices:3, wildChild=false
--- path=3, type=0, childrenLen=0, priority:1, indices:, wildChild=false//测试内容
userRouters.GET("/list", Index)
userRouters.GET("/list2", Index)
userRouters.GET("/list23", Index)
userRouters.GET("/list33", Index)
userRouters.GET("/liicq", Index)userRouters.GET("/lipar/:id/:sn", Index)
userRouters.GET("/lipar2", Index)//打印结果
# path=/admin/user/li, type=1, childrenLen=3, priority:7, indices:spi, wildChild=false
- path=st, type=0, childrenLen=2, priority:4, indices:23, wildChild=false
- path=par, type=0, childrenLen=2, priority:2, indices:/2, wildChild=false
- path=icq, type=0, childrenLen=0, priority:1, indices:, wildChild=false
## path=st, type=0, childrenLen=2, priority:4, indices:23, wildChild=false
-- path=2, type=0, childrenLen=1, priority:2, indices:3, wildChild=false
-- path=33, type=0, childrenLen=0, priority:1, indices:, wildChild=false
### path=2, type=0, childrenLen=1, priority:2, indices:3, wildChild=false
--- path=3, type=0, childrenLen=0, priority:1, indices:, wildChild=false
## path=par, type=0, childrenLen=2, priority:2, indices:/2, wildChild=false
-- path=/, type=0, childrenLen=1, priority:1, indices:, wildChild=true
-- path=2, type=0, childrenLen=0, priority:1, indices:, wildChild=false
### path=/, type=0, childrenLen=1, priority:1, indices:, wildChild=true
--- path=:id, type=2, childrenLen=1, priority:1, indices:, wildChild=false
#### path=:id, type=2, childrenLen=1, priority:1, indices:, wildChild=false
---- path=/, type=0, childrenLen=1, priority:1, indices:, wildChild=true
##### path=/, type=0, childrenLen=1, priority:1, indices:, wildChild=true
----- path=:sn, type=2, childrenLen=0, priority:1, indices:, wildChild=false

下篇文章了解一下gin启动都做了什么工作,中间件如何被调用,以及request是如何并发的

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/788543.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

ElasticSearch的常用数据类型

常见的数据类型 Text类型&#xff08;文本数据类型&#xff09; 用于索引全文值的字段&#xff0c;例如电子邮件的正文或产品的描述。这些字段是analyzed&#xff0c;也就是说&#xff0c;它们通过分析器传递&#xff0c;以便 在被索引之前将字符串转换为单个术语的列表。通过…

Clickhouse为什么如此快?

在大数据处理和分析领域&#xff0c;ClickHouse以其卓越的性能和高效的查询能力而备受瞩目。许多企业和开发者选择ClickHouse作为其数据处理的核心引擎&#xff0c;主要源于其出色的查询速度和数据处理能力。那么&#xff0c;ClickHouse为何能够如此快速地处理数据呢&#xff1…

radash 工具整理常用 API

正在替代 lodash 的新JS工具, 旧的 lodash 语法太老, 新的 radash 集合了 ES6 语法, 效率更高 安装 : npm i radash 常用API整理 : 数组 API : 1. 数组排序 alphabetical 按字母顺序, 正序倒序排列 import { alphabetical } from radashconst gods [{name: Ra,power: …

产品经理功法修炼(3)之产品设计

点击下载《产品经理功法修炼(3)之产品设计》 1. 前言 产品经理的能力修炼并非局限于某一技能的速成,而是需要全面参与到产品的整个生命周期中,通过不断的实践来逐步提升自己的各项能力。尽管在企业的日常运作中,我们不可能身兼数职去扮演每一个角色,但作为产品的核心负…

Go-Gin中优雅的实现参数校验,自定义错误消息提示

问题描述 在参数校验的时候我们一般会基于"github.com/go-playground/validator/v10"这个库给结构体加标签实现校验参数&#xff0c;当参数校验错误的时候&#xff0c;他的提示一般是英文的&#xff0c;怎么自定义参数错误提示呢&#xff1f;跟着我一步步来 注册校…

OpenAI 宣布, ChatGPT 网页端无需注册就能立即使用(2024年4月1日)

今天&#xff0c;OpenAI宣布&#xff0c;为了让更多人轻松体验人工智能的强大功能&#xff0c;现在无需注册账户即可立即使用 ChatGPT。这一变化是他们使命的核心部分&#xff0c;即让像 ChatGPT 这样的工具广泛可用&#xff0c;让世界各地的人们都能享受到 AI 带来的好处。 网…

PostgreSQL的学习心得和知识总结(一百三十五)|深入理解PostgreSQL数据库之查找 PostgreSQL C 代码中的内存泄漏

目录结构 注&#xff1a;提前言明 本文借鉴了以下博主、书籍或网站的内容&#xff0c;其列表如下&#xff1a; 1、参考书籍&#xff1a;《PostgreSQL数据库内核分析》 2、参考书籍&#xff1a;《数据库事务处理的艺术&#xff1a;事务管理与并发控制》 3、PostgreSQL数据库仓库…

【苍穹外卖】SkyApplication类启动报错

报的这个错 The PoM for com.sky:sky-common:jar:1.0-SNAPSHoT is missing, no dependency information available Maven里重新install一下就好

01-​JVM学习记录-类加载器

一、类加载器子系统 1. 作用-运输工具&#xff08;快递员&#xff09; 负责从文件系统或者网络中加载Class文件&#xff08;DNA元数据模板&#xff09;&#xff0c;Class文件开头有特定标识&#xff0c;魔术&#xff0c;咖啡杯壁&#xff08;class文件存于本地硬盘&#xff0c…

Java 设计模式系列:备忘录模式

简介 备忘录模式是一种软件设计模式&#xff0c;用于在不破坏封闭的前提下捕获一个对象的内部状态&#xff0c;并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。 备忘录模式提供了一种状态恢复的实现机制&#xff0c;使得用户可以方便地回到一个特定…

js动态替换字符串中所有匹配到的片段(replace + RegExp实现)

把字符串中匹配到的所有’A’替换成’哈’ <script>var text A12A34A56A789Avar result text.replace(new RegExp(A, g), 哈)console.log(result)//哈12哈34哈56哈789哈 </script>

版本排序,(如果 版本 是 1,1a,1.1a, 2, 2c , 1c , 1.2a, 3 , 5b , 5)进行排序

如果 版本 是 1&#xff0c;1a&#xff0c;1.1a&#xff0c; 2&#xff0c; 2c &#xff0c; 1c &#xff0c; 1.2a&#xff0c; 3 &#xff0c; 5b &#xff0c; 5 对上面的进行排序 利用 VersionComparator 导入依赖 <dependency><groupId>cn.hutool</groupId…

微信小程序开发学习笔记——4.8【小案例】初识wx.request获取网络请求并渲染至页面

>>跟着b站up主“咸虾米_”学习微信小程序开发中&#xff0c;把学习记录存到这方便后续查找。 课程连接&#xff1a;4.8.【小案例】初识wx.request获取网络请求并渲染至页面_哔哩哔哩_bilibili up主提供的网络请求常用接口&#xff1a; 随机猫咪&#xff0c;用来获取一些…

【Kotlin】委托模式

1 委托模式简介 委托模式的类图结构如下。 对应的 Kotlin 代码如下。 fun main() {var baseImpl BaseImpl()var baseWrapper BaseWrapper(baseImpl)baseWrapper.myFun1() // 打印: BaseImpl, myFun1baseWrapper.myFun2() // 打印: BaseImpl, myFun2 }interface Base {fun my…

非关系型数据库(缓存数据库)redis的基础认知与安装

目录 一.关系型数据库和非关系型数据库 关系型数据库 非关系型数据库 关系数据库与非关系型数据库的区别 ①非关系数据 关系型数据库 非关系型数据库产生背景 数据存储流向 非关系型数据库 关系数据库 二.redis的简介 1.概念 2.Redis 具有以下几个优点: 3.Redi…

Nginx请求upstream timed out 错误时通常会尝试重新请求上游服务器(504 Gateway Timeout)

重新记录一下这个重复的nginx请求的问题&#xff1a; 背景 一个导出报表任务&#xff0c;下载报表时&#xff0c;发生了导出超时&#xff1a;504 Gateway Timeout的错误。 504 Gateway Timeout的原因如下&#xff1a; Nginx配置问题&#xff1a;检查您的Nginx配置是否正确。…

测斜仪在边坡安全监测中的重要作用

边坡作为土木工程和地质工程领域中常见的结构形式&#xff0c;其稳定性直接关系到工程安全以及人民生命财产的安全。因此&#xff0c;对边坡进行精确、及时的监测是至关重要的。在众多边坡监测仪器中&#xff0c;测斜仪以其独特的优势在边坡安全监测中发挥着重要的作用。 测斜仪…

uniapp:小程序腾讯地图程序文件qqmap-wx-jssdk.js 文件一直找不到无法导入

先看问题&#xff1a; 在使用腾讯地图api时无法导入到qqmap-wx-jssdk.js文件 解决方法&#xff1a;1、打开qqmap-wx-jssdk.js最后一行 然后导入&#xff1a;这里是我的路径位置&#xff0c;可以根据自己的路径位置进行更改导入 最后在生命周期函数中输出&#xff1a; 运行效果…

vivado 高级编程功能1

适用于 7 系列、 UltraScale 和 UltraScale FPGA 和 MPSoC 的回读和验证 为 7 系列器件生成已加密文件和已经过身份验证的文件 注释 &#xff1a; 如需获取其它信息 &#xff0c; 请参阅《使用加密确保 7 系列 FPGA 比特流的安全》 ( XAPP1239 ) 。 要生成加密比特流…

设计模式之代理模式解析(下)

4&#xff09;远程代理介绍 远程代理(Remote Proxy) 使客户端程序可以访问在远程主机上的对象&#xff0c;远程代理对象承担了大部分的网络通信工作&#xff0c;并负责对远程业务方法的调用。 5&#xff09;虚拟代理介绍 1.概述 虚拟代理(Virtual Proxy) 对于一些占用系统资…