gin/middleware/main.go

53 lines
1.0 KiB
Go
Raw Permalink Normal View History

2024-09-18 00:04:45 +08:00
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"time"
)
//定义一个GIN中间件
func middleware() gin.HandlerFunc {
return func(c *gin.Context) {
t1 := time.Now()
fmt.Println("中间件开始执行了")
//设置变量到context的key中,可以通过GET取到
c.Set("request", "中间件")
//执行函数 拦截handler
c.Next()
status := c.Writer.Status()
fmt.Println("中间件执行完毕", status)
t2 := time.Since(t1)
fmt.Println("time: ", t2)
}
}
func main() {
//1.创建路由
r := gin.Default()
//注册中间件
r.Use(middleware())
//{}是为了代码规范
{
r.GET("/middleware", func(c *gin.Context) {
//取值
req, _ := c.Get("request")
fmt.Println("req:", req)
//页面接收
c.JSON(200, gin.H{"request": req})
})
//跟路由后面是定义的局部中间件
r.GET("/middleware2", middleware(), func(c *gin.Context) {
//取值
req, _ := c.Get("request")
fmt.Println("req:", req)
//页面接收
c.JSON(200, gin.H{"request": req})
})
}
r.Run(":8000")
}