From ae9606fd35c77e73260003ae1e0be334764e2a05 Mon Sep 17 00:00:00 2001 From: Will McCutchen Date: Wed, 28 Sep 2022 16:01:56 -0400 Subject: [PATCH] contrib/net/http: NewServeMux respects WithResourceNamer option (#1436) Fixes #1435. Co-authored-by: Andrew Glaude --- contrib/net/http/http.go | 5 ++++- contrib/net/http/http_test.go | 39 +++++++++++++++++++++++++++++++++-- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/contrib/net/http/http.go b/contrib/net/http/http.go index e3bc74244b..be24bfa57e 100644 --- a/contrib/net/http/http.go +++ b/contrib/net/http/http.go @@ -44,7 +44,10 @@ func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // get the resource associated to this request _, route := mux.Handler(r) - resource := r.Method + " " + route + resource := mux.cfg.resourceNamer(r) + if resource == "" { + resource = r.Method + " " + route + } TraceAndServe(mux.ServeMux, w, r, &ServeConfig{ Service: mux.cfg.serviceName, Resource: resource, diff --git a/contrib/net/http/http_test.go b/contrib/net/http/http_test.go index ec461571fc..71934da485 100644 --- a/contrib/net/http/http_test.go +++ b/contrib/net/http/http_test.go @@ -122,7 +122,38 @@ func TestNoStack(t *testing.T) { s := spans[0] assert.EqualError(spans[0].Tags()[ext.Error].(error), "500: Internal Server Error") assert.Equal("", s.Tags()[ext.ErrorStack]) +} + +func TestServeMuxUsesResourceNamer(t *testing.T) { + mt := mocktracer.Start() + defer mt.Stop() + + url := "/200" + r := httptest.NewRequest("GET", url, nil) + w := httptest.NewRecorder() + + resourceNamer := func(_ *http.Request) string { + return "custom-resource-name" + } + + router(WithResourceNamer(resourceNamer)).ServeHTTP(w, r) + + assert := assert.New(t) + assert.Equal(200, w.Code) + assert.Equal("OK\n", w.Body.String()) + + spans := mt.FinishedSpans() + assert.Equal(1, len(spans)) + s := spans[0] + assert.Equal("http.request", s.OperationName()) + assert.Equal("my-service", s.Tag(ext.ServiceName)) + assert.Equal("custom-resource-name", s.Tag(ext.ResourceName)) + assert.Equal("200", s.Tag(ext.HTTPCode)) + assert.Equal("GET", s.Tag(ext.HTTPMethod)) + assert.Equal("http://example.com"+url, s.Tag(ext.HTTPURL)) + assert.Equal(nil, s.Tag(ext.Error)) + assert.Equal("bar", s.Tag("foo")) } func TestAnalyticsSettings(t *testing.T) { @@ -250,8 +281,12 @@ func TestIgnoreRequestOption(t *testing.T) { } } -func router() http.Handler { - mux := NewServeMux(WithServiceName("my-service"), WithSpanOptions(tracer.Tag("foo", "bar"))) +func router(muxOpts ...Option) http.Handler { + defaultOpts := []Option{ + WithServiceName("my-service"), + WithSpanOptions(tracer.Tag("foo", "bar")), + } + mux := NewServeMux(append(defaultOpts, muxOpts...)...) mux.HandleFunc("/200", handler200) mux.HandleFunc("/500", handler500) return mux