Skip to content

Commit

Permalink
contrib/net/http: NewServeMux respects WithResourceNamer option (#1436)
Browse files Browse the repository at this point in the history
Fixes #1435.

Co-authored-by: Andrew Glaude <andrew.glaude@datadoghq.com>
  • Loading branch information
mccutchen and ajgajg1134 committed Sep 28, 2022
1 parent 8fdd9c8 commit f148b10
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
5 changes: 4 additions & 1 deletion contrib/net/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
39 changes: 37 additions & 2 deletions contrib/net/http/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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("<debug stack disabled>", 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) {
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit f148b10

Please sign in to comment.