You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
promhttp: implement WithXFromContext in terms of WithXFromRequest
This change adds WithLabelFromRequest and WithExemplarFromRequest
options and updates FromContext counterparts to be a convenience
wrappers for these options.
For example, without this change, setting a label based on
http.Request.Pattern requires some juggling with context:
var ctxHTTPRequestKey = httpRequestContext{}
type httpRequestContext struct {
*http.Request
}
func httpPatternFromContext(ctx context.Context) string {
r := ctx.Value(ctxHTTPRequestKey).(*httpRequestContext)
return r.Pattern
}
func instrumentHTTPHandler(h http.Handler) http.Handler {
h = promhttp.InstrumentHandlerCounter(httpRequestsTotal, h,
promhttp.WithLabelFromCtx("handler", httpPatternFromContext),
)
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var c httpRequestContext
ctx := context.WithValue(r.Context(), ctxHTTPRequestKey, &c)
r = r.WithContext(ctx)
c = httpRequestContext{r}
h.ServeHTTP(w, r)
})
}
promhttp.WithLabelFromRequest allows to access http.Request directly:
func instrumentHTTPHandler(h http.Handler) http.Handler {
return promhttp.InstrumentHandlerCounter(httpRequestsTotal, h,
promhttp.WithLabelFromRequest("handler", func(r *http.Request) string {
return r.Pattern
}),
)
}
0 commit comments