Skip to content

Conversation

tie
Copy link

@tie tie commented Aug 29, 2025

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
		}),
	)
}

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
			}),
		)
	}

Signed-off-by: Ivan Trubach <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant