Updated code based on Juliens comments (via Slack).

Signed-off-by: Peter Štibraný <peter.stibrany@grafana.com>
This commit is contained in:
Peter Štibraný 2020-02-19 11:57:20 +01:00
parent fe3fe5740e
commit a7d3a456d6

View File

@ -34,23 +34,20 @@ func ContextWithPath(ctx context.Context, path string) context.Context {
// ContextFromRequest returns a new context with identifiers of // ContextFromRequest returns a new context with identifiers of
// the request to be used later when logging the query. // the request to be used later when logging the query.
func ContextFromRequest(ctx context.Context, r *http.Request) context.Context { func ContextFromRequest(ctx context.Context, r *http.Request) context.Context {
reqCtxVal := map[string]string{ var ip string
"method": r.Method, if r.RemoteAddr != "" {
// r.RemoteAddr has no defined format, so don't return error if we cannot split it into IP:Port.
ip, _, _ = net.SplitHostPort(r.RemoteAddr)
} }
// r.RemoteAddr has no defined format, so don't return error if we cannot split it into IP:Port.
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
if ip != "" {
reqCtxVal["clientIP"] = ip
}
var path string var path string
if v := ctx.Value(pathParam); v != nil { if v := ctx.Value(pathParam); v != nil {
path = v.(string) path = v.(string)
reqCtxVal["path"] = path
} }
return promql.NewOriginContext(ctx, map[string]interface{}{ return promql.NewOriginContext(ctx, map[string]interface{}{
"httpRequest": reqCtxVal, "httpRequest": map[string]string{
"clientIP": ip,
"method": r.Method,
"path": path,
},
}) })
} }