gpt4 book ai didi

go - 如何在Go-gin中的中间件之间共享变量

转载 作者:行者123 更新时间:2023-12-01 22:04:30 26 4
gpt4 key购买 nike

例如在ExpressJS中,我的路线看起来像这样

router.patch('/:id/approve', AuthMiddleware.verifyToken,
AuthMiddleware.isSuperAdmin, AccommodationMiddleware.param, Accommodation.accommodationApprove);
我将全局变量,并在每个地方访问它 req.somevariable = somevariable Gin 有可能吗,然后怎么办?我需要跨中间件传递数据,我不知道如何

最佳答案

您可以将 Context 用于此类事情,这是一个示例:

package main

import (
"log"
"net/http"

"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)

type ParamsOne struct {
Username string `json:"username"`
}

type ParamsTwo struct {
Username string `json:"username"`
}

func first(c *gin.Context) {
c.Set("variable", "foo")
c.Next()
}

func second(c *gin.Context) {
v := c.MustGet("variable")
log.Printf("in middleware %s", v)
c.Next()
}

func main() {
r := gin.New()
r.Use(first)
r.Use(second)
r.POST("/", func(c *gin.Context) {
var f ParamsOne
if err := c.ShouldBindBodyWith(&f, binding.JSON); err != nil {
log.Printf("%+v", err)
}
log.Printf("%+v", f)
var ff ParamsTwo
if err := c.ShouldBindBodyWith(&ff, binding.JSON); err != nil {
log.Printf("%+v", err)
}
log.Printf("%+v", ff)
v := c.MustGet("variable")
log.Printf("in route %s", v)
c.IndentedJSON(http.StatusOK, f)
})
r.Run(":4000")
}
输出:
example$ ./example
[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env: export GIN_MODE=release
- using code: gin.SetMode(gin.ReleaseMode)

[GIN-debug] POST / --> main.main.func1 (3 handlers)
[GIN-debug] Listening and serving HTTP on :4000
2020/07/05 13:11:06 in middleware foo
2020/07/05 13:11:06 {Username:somename}
2020/07/05 13:11:06 {Username:somename}
2020/07/05 13:11:06 in route foo

关于go - 如何在Go-gin中的中间件之间共享变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62739044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com