dprfe04886
2016-11-30 14:50
浏览 502
已采纳

修复了“不应在上下文.WithValue中使用基本类型的字符串作为键”的问题

I am passing an uuid in using the Context and WithValue to subsequent functions that handle this *http.request. This uuid is was passed in the authorization header to a REST call to identify a person. The authorization token is verified and needs to accessible to check if the call is itself is authorized.

I used:

ctx := context.WithValue(r.Context(), string("principal_id"), *id)

But golint complains:

should not use basic type string as key in context.WithValue

What is the best option that could be used to retrieve this key that is not a basic type like a simple string?

图片转代码服务由CSDN问答提供 功能建议

我正在使用 Context WithValue 到处理此 * http.request 的后续函数。 此uuid在授权标头中传递到REST调用以识别人员。 授权令牌已验证,需要访问以检查呼叫本身是否已被授权。

我使用过:

  ctx:=  context.WithValue(r.Context(),string(“ principal_id”),* id)
   
 
 

但golint抱怨: < pre> 不应在上下文中使用基本类型字符串作为键。WithValue

什么是可以用来检索该键的最佳选择? 基本类型(如简单字符串)?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doqs8936 2016-11-30 14:53
    已采纳

    Just use a key type:

    type key int
    
    const (
        keyPrincipalID key = iota
        // ...
    )
    

    Since you've defined a separate type, it will never collide. Even if you have two packages, pkg1.key(0) != pkg2.key(0).

    See also: Go Blog about key collisions in context.

    点赞 打赏 评论
  • dongxie559554 2019-02-27 20:12

    Sharing a brief answer for the above question. GitHub Link In short, context.WithValue() needs interface{} type as keys and values.

    I hope this helps. Thank you.

    点赞 打赏 评论

相关推荐 更多相似问题