gin中间件
首先感谢七米老师的讲解:视频地址这个视频让我更加清晰的了解了gin中间件。
Gin框架允许开发者在处理请求的过程中,加入用户自己的钩子(Hook)函数。这个钩子函数就叫中间件,中间件适合处理一些公共的业务逻辑,比如登录认证、权限校验、数据分页、记录日志、耗时统计等。
定义中间件
Gin中的中间件必须是一个gin.HandlerFunc类型。例如我们像下面的代码一样定义一个统计请求耗时的中间件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
   |  func authMiddleware(doCheck bool) gin.HandlerFunc { 	return func(c *gin.Context) { 		if doCheck { 			 			 			 			 			 			 		} else { 			c.Abort() 		} 	} }
 
 
  | 
 
注册中间件
在gin框架中,我们可以为每个路由添加任意数量的中间件。



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
   | package main
  import ( 	"fmt" 	"github.com/gin-gonic/gin" 	"net/http" )
  func indexHandler(c *gin.Context) { 	c.JSON(http.StatusOK, gin.H{ 		"msg": "index", 	}) 	println("index") }
 
  func m2(c *gin.Context) { 	fmt.Println("m2 in ...") 	c.Next()  	 	fmt.Println("m2 out ...") }
 
  func m1(c *gin.Context) { 	fmt.Println("m1 in ...") 	c.Next()  	 	fmt.Println("m1 out ...") }
  func main() { 	r := gin.Default()
  	r.GET("/index", m1, m2, indexHandler)
  	r.Run(":9090") }
 
   | 
 
上程序运行结果为:

为全局路由注册
1
   | r.Use(m1, m2, authMiddleware(true)) 
   | 
 
为某个路由单独注册
1 2 3 4 5 6 7 8
   |  	r.GET("/test2", StatCost(), func(c *gin.Context) { 		name := c.MustGet("name").(string)  		log.Println(name) 		c.JSON(http.StatusOK, gin.H{ 			"message": "Hello world!", 		}) 	})
 
  | 
 
为路由组注册中间件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   |  shopGroup := r.Group("/shop", StatCost()) {     shopGroup.GET("/index", func(c *gin.Context) {...})     ... }
 
  shopGroup := r.Group("/shop") shopGroup.Use(StatCost()) {     shopGroup.GET("/index", func(c *gin.Context) {...})     ... }
 
 
  |