fix context keys

This commit is contained in:
Caleb Doxsey 2022-07-26 13:34:43 -06:00
parent 7adda15c75
commit e6fe3b0ceb
3 changed files with 16 additions and 9 deletions

View file

@ -322,13 +322,20 @@ func TestLoadBalancer(t *testing.T) {
if !assert.NoError(t, err) {
return distribution
}
defer res.Body.Close()
bs, err := io.ReadAll(res.Body)
if !assert.NoError(t, err) {
return distribution
}
var result struct {
Hostname string `json:"hostname"`
}
err = json.NewDecoder(res.Body).Decode(&result)
_ = res.Body.Close()
assert.NoError(t, err)
err = json.Unmarshal(bs, &result)
if !assert.NoError(t, err, "invalid json: %s", bs) {
return distribution
}
distribution[result.Hostname]++
}

View file

@ -11,16 +11,16 @@ import (
const headerName = "x-request-id"
var contextKey struct{}
type contextKey struct{}
// WithValue returns a new context from the parent context with a request id value set.
func WithValue(parent context.Context, requestID string) context.Context {
return context.WithValue(parent, contextKey, requestID)
return context.WithValue(parent, contextKey{}, requestID)
}
// FromContext gets the request id from a context.
func FromContext(ctx context.Context) string {
if id, ok := ctx.Value(contextKey).(string); ok {
if id, ok := ctx.Value(contextKey{}).(string); ok {
return id
}
return ""

View file

@ -33,11 +33,11 @@ func (nilQuerier) Query(ctx context.Context, in *databroker.QueryRequest, opts .
return nil, status.Error(codes.NotFound, "not found")
}
var querierKey struct{}
type querierKey struct{}
// GetQuerier gets the databroker Querier from the context.
func GetQuerier(ctx context.Context) Querier {
q, ok := ctx.Value(querierKey).(Querier)
q, ok := ctx.Value(querierKey{}).(Querier)
if !ok {
q = nilQuerier{}
}
@ -46,7 +46,7 @@ func GetQuerier(ctx context.Context) Querier {
// WithQuerier sets the databroker Querier on a context.
func WithQuerier(ctx context.Context, querier Querier) context.Context {
return context.WithValue(ctx, querierKey, querier)
return context.WithValue(ctx, querierKey{}, querier)
}
type staticQuerier struct {