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.hqwc.cn/news/586160.html

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

相关文章

3款必知的AI写作软件,智能写文效率高

在当今信息爆炸的时代&#xff0c;写作已经成为人们生活和工作中不可或缺的一部分。然而&#xff0c;随着人们对高效率和高质量写作需求的不断增加&#xff0c;人工智能写作软件应运而生。这些AI写作软件凭借其强大的语言处理能力和智能算法&#xff0c;为写作者们提供了全新的…

郭天祥新概念51单片机(第四期读书笔记)

时钟周期、状态周期、机器周期、指令周期与晶振频率之间的关系 1、晶振频率与脉冲的关系 假设单片机的晶振频率是12MHz&#xff0c;那么它的一个脉冲为1/12微秒&#xff1b;晶振单位时间发出的脉冲则为&#xff1a; 12 ∗ 1 0 6 12*10^6 12∗106。 假设单片机的晶振频率是4MH…

LeetCode-240. 搜索二维矩阵 II【数组 二分查找 分治 矩阵】

LeetCode-240. 搜索二维矩阵 II【数组 二分查找 分治 矩阵】 题目描述&#xff1a;解题思路一&#xff1a;从左下角或者右上角元素出发&#xff0c;来寻找target。解题思路二&#xff1a;右上角元素&#xff0c;代码解题思路三&#xff1a;暴力也能过解题思路四&#xff1a;二分…

成都直播基地 天府新区产业园能获得哪些政府支持

为了推动成都直播产业的快速发展&#xff0c;政府出台了一系列政策措施&#xff0c;为成都直播基地提供了全方位的支持。本篇文章将为您具体解析入驻成都直播基地 天府新区产业园 天府锋巢直播产业基地都能获得哪些政府支持。 首先&#xff0c;天府新区作为成都市的重要发展区…

Three.js——创建场景、渲染三维对象、添加灯光、添加阴影、添加雾化

个人简介 &#x1f440;个人主页&#xff1a; 前端杂货铺 &#x1f64b;‍♂️学习方向&#xff1a; 主攻前端方向&#xff0c;正逐渐往全干发展 &#x1f4c3;个人状态&#xff1a; 研发工程师&#xff0c;现效力于中国工业软件事业 &#x1f680;人生格言&#xff1a; 积跬步…

2024年最受欢迎的 19 个 VS Code 主题排行榜

博主猫头虎的技术世界 &#x1f31f; 欢迎来到猫头虎的博客 — 探索技术的无限可能&#xff01; 专栏链接&#xff1a; &#x1f517; 精选专栏&#xff1a; 《面试题大全》 — 面试准备的宝典&#xff01;《IDEA开发秘籍》 — 提升你的IDEA技能&#xff01;《100天精通鸿蒙》 …

软件测试-用例篇

目录 1 测试用例的基本要素2 测试用例给我们带来的好处3 测试用例的设计方法3.1 基于需求进行测试用例的设计3.1.1 功能需求测试分析3.1.2 非功能需求测试分析 4 具体的设计方法4.1 等价类4.2 边界值4.3 错误猜测法4.4 场景设计法4.5 因果图4.5.1 因果图需要掌握的基本知识4.5.…

快速入门Linux,Linux岗位有哪些?(一)

文章目录 Linux与Linux运维操作系统&#xff1f;操作系统图解 认识LinuxLinux受欢迎的原因什么是Linux运维Linux运维岗位Linux运维岗位职责Linux运维架构师岗位职责Linux运维职业发展路线计算机硬件分类运维人员的三大核心职责 运维人员工作&#xff08;服务器&#xff09;什么…

Qt实现Kermit协议(一)

1 概述 Kermit文件运输协议提供了一条从大型计算机下载文件到微机的途径。它已被用于进行公用数据传输。 其特性如下: Kermit文件运输协议是一个半双工的通信协议。它支持7位ASCII字符。数据以可多达96字节长度的可变长度的分组形式传输。对每个被传送分组需要一个确认。Kerm…

【RISC-V】如何使用release的risc-v gnu toolchain

riscv64-elf-ubuntu-22.04-gcc-nightly-2024.03.01-nightly.tar.gz 首先去release页面中获取相应的压缩包 将压缩包解压到想解压的位置&#xff0c;这里我选择了 mv Downloads/riscv64-elf-ubuntu-22.04-gcc-nightly-2024.03.01-nightly.tar.gz riscv64-tool-chain/然后解压…

如何将Maven与TestNG集成

我们已经讨论了如何在maven中执行单元测试用例&#xff0c;但那些是JUnit测试用例&#xff0c;而不是TestNG。当maven使用“mvn test”命令进入测试阶段时&#xff0c;这些用例被执行。 本文将介绍如何将Maven与TestNG集成&#xff0c;并在maven进入测试阶段时执行TestNG测试。…

YUM安装MySQL报错合集

报错信息 Error:Problem: cannot install the best candidate for the job- nothing provides libcrypto.so.10()(64bit) needed by mysql-community-server-8.0.36-1.el7.x86_64 from mysql80-community- nothing provides libssl.so.10()(64bit) needed by mysql-community-…