Gin爲框架入門——中間件和自定義上下文

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")
}

編譯運行。

參考:

https://www.cnblogs.com/iiiiiher/p/12202091.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章