go-中间件的使用
中间件介绍
- Gin框架允许开发者在处理请求的过程中加入用户自己的钩子(Hook)函数
- 这个钩子函数就是中间件,中间件适合处理一些公共的业务逻辑
- 比如登录认证,权限校验,数据分页,记录日志,耗时统计
1.定义全局中间件
package mainimport ("fmt""github.com/gin-gonic/gin"
)// 4.定义全局中间件
func MiddleWare() gin.HandlerFunc {return func(c *gin.Context) {fmt.Println("我是一个全局中间件")}
}func main() {// 1.实力化引擎r := gin.Default()// 全局使用中间件r.Use(MiddleWare())// 2. 配置路由r.GET("/hello", func(c *gin.Context) {fmt.Println("执行hello")c.JSON(200, gin.H{"msg": "执行成功"})})// 3. 启动服务fmt.Println("服务启动成功:http://127.0.0.1:8080/hello")r.Run(":8080")
}
2.定义局部中间件
func main() {// 1.实力化引擎r := gin.Default()// 2. 配置路由r.GET("/hello", func(c *gin.Context) {fmt.Println("执行hello")c.JSON(200, gin.H{"msg": "执行成功"})})// 局部使用中间件r.GET("/hook", MiddleWare(), func(c *gin.Context) {fmt.Println("执行hello")c.JSON(200, gin.H{"msg": "执行hook成功"})})// 3. 启动服务fmt.Println("服务启动成功:http://127.0.0.1:8080/hello")r.Run(":8080")
}
中间件的应用
package mainimport ("fmt""github.com/gin-gonic/gin"
)// 4.定义全局中间件
func Auth() gin.HandlerFunc {return func(c *gin.Context) {// 1. 获取tokentoken := c.Request.Header.Get("token")fmt.Println(token)if token != "123456" {c.String(403, "token验证失败")c.Abort() // 终止请求return}c.Next()}
}func main() {// 1.实力化引擎r := gin.Default()// 2. 配置路由r.GET("/index", func(c *gin.Context) {c.JSON(200, gin.H{"msg": "index无需登录可以访问"})})r.GET("/home", Auth(), func(c *gin.Context) {c.JSON(200, gin.H{"msg": "home需登录验证才能访问"})})// 3. 启动服务fmt.Println("服务启动成功:http://127.0.0.1:8080/hello")r.Run(":8080")
}
token验证失败直接反馈403
验证成功才能访问