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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值