Skip to content

Commit

Permalink
gorilla/mux: allow setting custom span options (DataDog#320)
Browse files Browse the repository at this point in the history
  • Loading branch information
gbbr authored and mingrammer committed Dec 22, 2020
1 parent b7c455c commit a3ab876
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
1 change: 1 addition & 0 deletions contrib/gorilla/mux/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
spanopts = append(spanopts, tracer.Tag("mux.host", h))
}
}
spanopts = append(spanopts, r.config.spanOpts...)
resource := req.Method + " " + route
httputil.TraceAndServe(r.Router, w, req, r.config.serviceName, resource, spanopts...)
}
16 changes: 16 additions & 0 deletions contrib/gorilla/mux/mux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (

"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/mocktracer"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"

"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -92,6 +93,21 @@ func TestDomain(t *testing.T) {
assert.Equal("localhost", spans[0].Tag("mux.host"))
}

func TestSpanOptions(t *testing.T) {
assert := assert.New(t)
mt := mocktracer.Start()
defer mt.Stop()
mux := NewRouter(WithSpanOptions(tracer.Tag(ext.SamplingPriority, 2)))
mux.Handle("/200", okHandler()).Host("localhost")
r := httptest.NewRequest("GET", "http://localhost/200", nil)
w := httptest.NewRecorder()
mux.ServeHTTP(w, r)

spans := mt.FinishedSpans()
assert.Equal(1, len(spans))
assert.Equal(2, spans[0].Tag(ext.SamplingPriority))
}

// TestImplementingMethods is a regression tests asserting that all the mux.Router methods
// returning the router will return the modified traced version of it and not the original
// router.
Expand Down
15 changes: 14 additions & 1 deletion contrib/gorilla/mux/option.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package mux

type routerConfig struct{ serviceName string }
import "gopkg.in/DataDog/dd-trace-go.v1/ddtrace"

type routerConfig struct {
serviceName string
spanOpts []ddtrace.StartSpanOption // additional span options to be applied
}

// RouterOption represents an option that can be passed to NewRouter.
type RouterOption func(*routerConfig)
Expand All @@ -15,3 +20,11 @@ func WithServiceName(name string) RouterOption {
cfg.serviceName = name
}
}

// WithSpanOptions applies the given set of options to the spans started
// by the router.
func WithSpanOptions(opts ...ddtrace.StartSpanOption) RouterOption {
return func(cfg *routerConfig) {
cfg.spanOpts = opts
}
}

0 comments on commit a3ab876

Please sign in to comment.