Skip to content

Commit

Permalink
contrib/net/http: add dynamic resource naming (#1142)
Browse files Browse the repository at this point in the history
contrib/net/http: added dynamic resource naming

Co-authored-by: Gabriel Aszalos <gabriel.aszalos@gmail.com>
  • Loading branch information
jcogilvie and gbbr committed Apr 28, 2022
1 parent 11df452 commit c7e6cbe
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
4 changes: 4 additions & 0 deletions contrib/net/http/http.go
Expand Up @@ -53,6 +53,7 @@ func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

// WrapHandler wraps an http.Handler with tracing using the given service and resource.
// If the WithResourceNamer option is provided as part of opts, it will take precedence over the resource argument.
func WrapHandler(h http.Handler, service, resource string, opts ...Option) http.Handler {
cfg := new(config)
defaults(cfg)
Expand All @@ -65,6 +66,9 @@ func WrapHandler(h http.Handler, service, resource string, opts ...Option) http.
h.ServeHTTP(w, req)
return
}
if r := cfg.resourceNamer(req); r != "" {
resource = r
}
TraceAndServe(h, w, req, &ServeConfig{
Service: service,
Resource: resource,
Expand Down
9 changes: 9 additions & 0 deletions contrib/net/http/option.go
Expand Up @@ -22,6 +22,7 @@ type config struct {
spanOpts []ddtrace.StartSpanOption
finishOpts []ddtrace.FinishOption
ignoreRequest func(*http.Request) bool
resourceNamer func(*http.Request) string
}

// MuxOption has been deprecated in favor of Option.
Expand All @@ -45,6 +46,7 @@ func defaults(cfg *config) {
cfg.spanOpts = append(cfg.spanOpts, tracer.Tag(ext.EventSampleRate, cfg.analyticsRate))
}
cfg.ignoreRequest = func(_ *http.Request) bool { return false }
cfg.resourceNamer = func(_ *http.Request) string { return "" }
}

// WithIgnoreRequest holds the function to use for determining if the
Expand Down Expand Up @@ -95,6 +97,13 @@ func WithSpanOptions(opts ...ddtrace.StartSpanOption) Option {
}
}

// WithResourceNamer populates the name of a resource based on a custom function.
func WithResourceNamer(namer func(req *http.Request) string) Option {
return func(cfg *config) {
cfg.resourceNamer = namer
}
}

// NoDebugStack prevents stack traces from being attached to spans finishing
// with an error. This is useful in situations where errors are frequent and
// performance is critical.
Expand Down

0 comments on commit c7e6cbe

Please sign in to comment.