Fix “should not use basic type string as key in context.WithValue” golint

送分小仙女□ 提交于 2020-05-07 12:25:48

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/40891345/fix-should-not-use-basic-type-string-as-key-in-context-withvalue-golint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!