Use struct{} as underlying type for context keys (#6965)

This is an alternative to #6963.

Signed-off-by: beorn7 <beorn@grafana.com>
This commit is contained in:
Björn Rabenstein 2020-03-11 15:05:35 +01:00 committed by GitHub
parent 4dfbf328f2
commit bc703b6456
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 10 deletions

View file

@ -152,9 +152,7 @@ type query struct {
ng *Engine
}
type queryCtx int
var queryOrigin queryCtx
type queryOrigin struct{}
// Statement implements the Query interface.
func (q *query) Statement() parser.Statement {
@ -441,7 +439,7 @@ func (ng *Engine) exec(ctx context.Context, q *query) (v parser.Value, w storage
f = append(f, "error", err)
}
f = append(f, "stats", stats.NewQueryStats(q.Stats()))
if origin := ctx.Value(queryOrigin); origin != nil {
if origin := ctx.Value(queryOrigin{}); origin != nil {
for k, v := range origin.(map[string]interface{}) {
f = append(f, k, v)
}
@ -2097,7 +2095,7 @@ func shouldDropMetricName(op parser.ItemType) bool {
// NewOriginContext returns a new context with data about the origin attached.
func NewOriginContext(ctx context.Context, data map[string]interface{}) context.Context {
return context.WithValue(ctx, queryOrigin, data)
return context.WithValue(ctx, queryOrigin{}, data)
}
func formatDate(t time.Time) string {

View file

@ -21,14 +21,12 @@ import (
"github.com/prometheus/prometheus/promql"
)
type ctxParam int
var pathParam ctxParam
type pathParam struct{}
// ContextWithPath returns a new context with the given path to be used later
// when logging the query.
func ContextWithPath(ctx context.Context, path string) context.Context {
return context.WithValue(ctx, pathParam, path)
return context.WithValue(ctx, pathParam{}, path)
}
// ContextFromRequest returns a new context with identifiers of
@ -40,7 +38,7 @@ func ContextFromRequest(ctx context.Context, r *http.Request) context.Context {
ip, _, _ = net.SplitHostPort(r.RemoteAddr)
}
var path string
if v := ctx.Value(pathParam); v != nil {
if v := ctx.Value(pathParam{}); v != nil {
path = v.(string)
}
return promql.NewOriginContext(ctx, map[string]interface{}{