func main() {
// 创建一个r,这一行相当于下面几行
// 默认使用了Logger(), Recovery()
r := gin.Default()


// 相当于上面的作用
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
}
package main
import (
"fmt"
"time"

"github.com/gin-gonic/gin"
)


// 定义中间件
func SelfDefinedMiddleWare() gin.HandlerFunc {
return func(c *gin.Context) {
t1 := time.Now()
fmt.Println("开始执行中间件")
// 设置您的变量到Context的key中,后续可在控制器逻辑中通过Get()拿到
c.Set("key1", "value1")
status := c.Writer.Status()
fmt.Println("结束执行中间件", status)
t2 := time.Since(t1)
fmt.Println("time:", t2)
}
}


func main() {
// 默认使用了2个中间件Logger(), Recovery()
r := gin.Default()
// 注册中间件
r.Use(SelfDefinedMiddleWare())
{
r.GET("/test_global_middleWare", func(c *gin.Context) {
value1, _ := c.Get("key1")
fmt.Println("value1:", value1)
c.JSON(200, gin.H{"value1": value1})
})
}
r.Run()
}


很显然,一个自定义的全局 Middleware 就已经起作用了:

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.


[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)


[GIN-debug] GET /test_global_middleWare --> main.main.func1 (4 handlers)
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080
开始执行中间件
结束执行中间件 200
time: 295µs
value1: value1
[GIN] 2021/10/14 - 10:28:50 | 200 |      1.3293ms |       127.0.0.1 | GET      "/test_global_middleWare"