在使用gin時(shí),如果想在context中保存一些變量,比如用戶的id,通常的做法是放到context的Keys變量中,這樣做的話,我們每次取的時(shí)候,都得進(jìn)行類型轉(zhuǎn)化。
我習(xí)慣的做法是,定義自己的context,再在context中定義自己想要保存的變量,就像下面這樣。
type context struct {
*gin.Context
userId int64 // 用戶id
}
然后定義handler
func do(c *context) {
fmt.Println(c.userId)
}
然后,怎樣把它注冊(cè)進(jìn)Engine里面呢,這里還需要一個(gè)函數(shù)進(jìn)行處理一下
type HandlerFunc func(*context)
func handler(handler HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
context := new(context)
context.Context = c
if userId, ok := c.Keys[keyUserId]; ok {
context.userId = userId.(int64)
}
handler(context)
}
}
接下來(lái),就可以注冊(cè)進(jìn)進(jìn)Engine里面了
var Engine = gin.New()
Engine.GET("/hi",handler(do))