Gin中的中間件和上下文傳值:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
//--------------------------------------------//
type MyContext struct {
*gin.Context
userId int64
}
//
func do(c *MyContext) {
fmt.Println(c.userId)//123456
}
//
type HandlerFunc func(* MyContext)
//
func MyHandler(handler HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
//
ctx := new(MyContext)
ctx.Context = c
//
//if userId, ok := c.Keys["keyUserId"]; ok {
if userId, ok := c.Get("keyUserId"); ok {
ctx.userId = userId.(int64)
fmt.Println(c.Get("mykey2"))//m1 true
}
//
handler(ctx)
}
}
//--------------------------------------------//
//
//--------------------------------------------//
func MyMiddleware(ctx *gin.Context) {
ctx.Set("mykey", 10)
ctx.Set("mykey2", "m1")
ctx.Set("keyUserId", int64(123456))//
}
//--------------------------------------------//
func main() {
//生產模式
//gin.SetMode(gin.ReleaseMode)
//無中間件
router := gin.New()
//自定義中間件 + 自定義上下文
router.GET("/hi", MyMiddleware, MyHandler(do))
//運行Gin
router.Run(":8080")
}
編譯運行。
參考: