debuggoCritical
Fix "should not use basic type string as key in context.WithValue" golint
Viewed 0 times
keyfixgolintshouldusecontextbasicnotstringtype
Problem
I am passing an uuid in using the
I used:
But golint complains:
What is the best option that could be used to retrieve this key that is not a basic type like a simple string?
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.WithValueWhat is the best option that could be used to retrieve this key that is not a basic type like a simple string?
Solution
Just use a key type:
Since you've defined a separate type, it will never collide. Even if you have two packages,
See also: Go Blog about key collisions in context.
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.
Context
Stack Overflow Q#40891345, score: 141
Revisions (0)
No revisions yet.