我有一段非常简单的代码。一个中间件应用于所有路由。在此中间件中,读取标头字段“x-sentinel-tenant”。如果为空,则返回错误。如果它具有某个值,则将提取该值并将其设置在请求上下文中以供以后使用。
这是我的中间件代码
// VerifyTenant ensures that the user has added tenant information in the header
func VerifyTenant(c *gin.Context) {
requestTenant := c.Request.Header.Get("x-tenant")
if requestTenant == "" {
c.AbortWithStatusJSON(
http.StatusBadRequest,
views.GenerateErrorResponse(
http.StatusBadRequest,
"Please add tenant in the header.",
c.Request.URL.Path,
),
)
return
}
c.Request = c.Request.WithContext(context.WithValue(c, tenant, requestTenant))
}
Run Code Online (Sandbox Code Playgroud)
当我尝试在代码的后面部分访问此上下文时,以下是将鼠标悬停在 ctx 值上时获取数据的方式。
我不确定我做错了什么。这是一段相当简单的代码,其行为非常有趣。任何线索将不胜感激。谢谢
当我更新上下文时,我希望将“租户”添加为另一个字段。但这并没有发生。多个值不能在同一上下文中共存吗?
我的问题 - 如何在 gin 请求上下文中正确设置多个值 这是我尝试访问租户的方式
return ctx.Value("Context").(context.Context).Value("tenant").(string)
Run Code Online (Sandbox Code Playgroud)
Ari*_*ith 17
https://pkg.go.dev/github.com/gin-gonic/gin?tab=doc#Context.Set
func (*Context) Set
正是你想要的。一个例子是:
func VerifyTenant(ctx *gin.Context) {
requestTenant := ctx.GetHeader("x-tenant")
if requestTenant == "" {
// Abort
return
}
ctx.Set("x-tenant", requestTenant)
}
func Test(ctx *gin.Context){
// when you need to get the value of "x-tenant"
requestTenant := ctx.GetString("x-tenant")
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
32339 次 |
最近记录: |