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

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:

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

But golint complains:

  1. 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?

Just use a key type:

  1. type key int
  2. const (
  3. keyPrincipalID key = iota
  4. // ...
  5. )

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.

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.

ft_authoradmin  ft_create_time2019-06-19 11:22
 ft_update_time2019-06-19 11:23