所有的请求都会经过中间件
示例代码:
package main import ( "fmt" "github.com/gin-gonic/gin" "time" ) func main() { engine := gin.Default() engine.Use(func(context *gin.Context) { s := time.Now() fmt.Println("Start middleware") context.Set("request", "Middleware") l := time.Now().Sub(s) fmt.Println("Time:", l) }) engine.GET("/index", func(context *gin.Context) { content, exists := context.Get("reques") if !exists { content = "null" } context.JSON(200, gin.H{ "request": content, }) }) engine.GET("/user", func(context *gin.Context) { content, exists := context.Get("request") if !exists { content = "null" } context.JSON(200, gin.H{ "message": content, }) }) engine.Run("localhost:8080") }
在代码中,定义一个中间件,并且设置了一个参数“request”,值为“middleware”,在下面的两个请求中,都取到了该参数
结果可见,两个请求都捕获了request参数
标签:engine,--,request,中间件,content,context,gin,Gin From: https://www.cnblogs.com/99kol/p/17309560.html