源码
github.com/zsl10/gin-e…
实例
package main
import (
"fmt"
"time"
"github.com/gin-gonic/gin"
)
// 定义中间件
func MiddleWare() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
fmt.Println("中间件开始执行了")
c.Set("request", "中间件")
// 执行路由函数
c.Next()
status := c.Writer.Status()
fmt.Println("中间件执行完毕", status)
t2 := time.Since(t)
fmt.Println("time:", t2)
}
}
func main() {
r := gin.Default()
r.Use(MiddleWare())
{
r.GET("/md2", func(c *gin.Context) {
req, _ := c.Get("request")
fmt.Println("request:", req)
c.JSON(200, gin.H{"request": req})
})
}
r.Run(":8080")
}
中间件开始执行了
request: 中间件
中间件执行完毕 200
time: 91.315µs
[GIN] 2020/01/06 - 16:36:31 | 200 | 101.12µs | 127.0.0.1 | GET /md2