【Golang】Gin框架中间件学习笔记

Gin框架中间件

文章介绍了Gin框架路由中间件和全局中间件的实现方式和常见的流程控制手段,最后介绍了中间件之间进行数据传输的方式。

概念介绍

Gin框架允许开发者在处理请求的过程中,加入用户自己的钩子函数。这个钩子函数被称为中间件,中间件适合处理一些公共的业务逻辑,比如登录认证、权限校验、数据分页、记录日志、耗时统计。中间件就是匹配路由前和匹配路由完成后执行的一系列操作。

路由中间件

如下面的例子,在注册GET函数时,传入了三个方法。这样程序就会分别在访问/test/login开始和结束的时候分别调用一次Hello函数。也就是说,这三个函数的执行顺序为Hello->Login->Hello。通过下文的Next()和Abort()函数,可以对这一执行顺序进行修改。

func Hello(c *gin.Context) {
	fmt.Println("hello")
}

func TestRouter(router *gin.Engine) {

	testRouter := router.Group("/test")
	testRouter.GET("/login", Hello, controller.TestController{}.Login, Hello)
}

流程控制手段

Next()

下面是Next函数的源码。

// Next should be used only inside middleware.
// It executes the pending handlers in the chain inside the calling handler.
// See example in GitHub.
func (c *Context) Next() {
	c.index++
	for c.index < int8(len(c.handlers)) {
		c.handlers[c.index](c)
		c.index++
	}
}

Next()相当于给将当前函数暂停,让系统先执行剩下的所有函数,执行完后,再返回继续执行当前函数。如果剩下的函数中也有Next(),则也是重复相同的步骤,类似于一个递归的过程。假如需要实现一个统计服务器处理时间的函数,可以按照下面的方法来实现。

func cntTime(c *gin.Context) {
	now := time.Now()
	c.Next()
	log.Printf("this function call costs %v ms.\n", time.Since(now).Milliseconds())
}

//为了方便看出效果,我们增加一个3秒的暂停。
func Ok(c *gin.Context) {
	time.Sleep(time.Second * 3)
	t.Success(c, gin.H{})
}

func TestRouter(router *gin.Engine) {

	testRouter := router.Group("/test")
	testRouter.GET("/ok", cntTime, Ok)
}

在这里插入图片描述
打印了20:55:56 app | 2024/06/20 20:55:56 this function call costs 3005 ms.

Abort()

c.Abort()会让当前handle函数执行完后,退出处理该路由,不执行后面的handle函数。下面这个例子中,OK函数就不会被执行了。

func abort(c *gin.Context) {
	c.Abort()
}
func TestRouter(router *gin.Engine) {

	testRouter := router.Group("/test")
	testRouter.GET("/ok", cntTime, abort, controller.TestController{}.Ok)
}

全局中间件

如果我们有个中间件添加给所有路由处理函数,比如我们要统计所有请求的执行时间,一个个添加上文的cntTime未免太过麻烦。因此,go语言中有全局中间件,可以一次性给当前组所有的路由处理函数添加中间件。

func cntTime(c *gin.Context) {
	now := time.Now()
	c.Next()
	log.Printf("this function call costs %v ms.\n", time.Since(now).Milliseconds())
}

func TestRouter(router *gin.Engine) {
	testRouter := router.Group("/test", cntTime)
	testRouter.GET("/ok", controller.TestController{}.Ok)
	testRouter.GET("/login", controller.TestController{}.Login)
	testRouter.GET("/html", controller.TestController{}.Html)
	testRouter.POST("/baidu", controller.TestController{}.Baidu)
	testRouter.POST("/xml", controller.TestController{}.Xml)
}

或者,我们也可以使用Use函数,在程序的执行过程中,添加中间件。

testRouter.Use(cntTime)

// Use adds middleware to the group, see example code in GitHub.
func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {
	group.Handlers = append(group.Handlers, middleware...)
	return group.returnObj()
}

上面是Use的使用方式和实现源码,可以看到,Use函数将middleware中的函数,逐个添加到了当前组的执行函数中,并返回了执行函数列表更新过后的RouterGroup。
那如果我们按照下面的方式,在程序的中间绑定了这个中间件。

func TestRouter(router *gin.Engine) {

	testRouter := router.Group("/test")

	testRouter.GET("/ok", controller.TestController{}.Ok)
	testRouter.GET("/login", controller.TestController{}.Login)
	testRouter.GET("/html", controller.TestController{}.Html)
	testRouter.Use(cntTime)
	testRouter.POST("/baidu", controller.TestController{}.Baidu)
	testRouter.POST("/xml", controller.TestController{}.Xml)
}

那么就只有Use下面的这些转发路由,才会在执行之前调用cntTime,开始计算执行时间。如下图,只有POST方法打印了执行时间。
在这里插入图片描述

通过context进行通信

当我们需要在不同中间件或者Controller之间进行数据传输的时候,可以通过使用
gin.Context下的Get和Set函数进行通信,如下所示。

func (t TestController) Ok(c *gin.Context) {
	now, _ := c.Get("time")
	t.Success(c, gin.H{"now": now})
}

func CntTime(c *gin.Context) {
	now := time.Now()
	c.Set("time", now.Format("2006-01-02 15:04:05"))
	c.Next()
	log.Printf("this function call costs %v ms.\n", time.Since(now).Milliseconds())

}

func TestRouter(router *gin.Engine) {

	testRouter := router.Group("/test",CntTime)
	{
		testRouter.GET("/ok", Ok)
    }
}

在调用Ok时,成功获取到了时间。
在这里插入图片描述

需要注意的是,当我们在中间件中,使用协程对gin.Context进行操作时,需要通过c.Copy(),获取一份副本。因为主程序在进行的同时,也会对context进行操作,如果两边同时操作同一个context对象,会引发并发问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值