http

package module
v0.0.0-...-1bc2693 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 17, 2024 License: Apache-2.0, BSD-3-Clause Imports: 17 Imported by: 12

Documentation

Overview

Package http provides functions to trace the net/http package (https://golang.org/pkg/net/http).

Example
package main

import (
	"net/http"

	httptrace "github.com/DataDog/dd-trace-go/v2/contrib/net/http"
)

func main() {
	mux := httptrace.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello World!\n"))
	})
	http.ListenAndServe(":8080", mux)
}
Output:

Example (WithServiceName)
package main

import (
	"net/http"

	httptrace "github.com/DataDog/dd-trace-go/v2/contrib/net/http"
)

func main() {
	mux := httptrace.NewServeMux(httptrace.WithService("my-service"))
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("Hello World!\n"))
	})
	http.ListenAndServe(":8080", mux)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func TraceAndServe

func TraceAndServe(h http.Handler, w http.ResponseWriter, r *http.Request, cfg *ServeConfig)

TraceAndServe serves the handler h using the given ResponseWriter and Request, applying tracing according to the specified config.

Example
package main

import (
	"net/http"

	httptrace "github.com/DataDog/dd-trace-go/v2/contrib/net/http"
)

func main() {
	mux := http.NewServeMux()
	mux.Handle("/", traceMiddleware(mux, http.HandlerFunc(Index)))
	http.ListenAndServe(":8080", mux)
}

func Index(w http.ResponseWriter, _ *http.Request) {
	w.Write([]byte("Hello World!\n"))
}

func traceMiddleware(mux *http.ServeMux, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, route := mux.Handler(r)
		resource := r.Method + " " + route
		httptrace.TraceAndServe(next, w, r, &httptrace.ServeConfig{
			Service:     "http.router",
			Resource:    resource,
			QueryParams: true,
		})
	})
}
Output:

func WrapClient

func WrapClient(c *http.Client, opts ...RoundTripperOption) *http.Client

WrapClient modifies the given client's transport to augment it with tracing and returns it.

Example

ExampleWrapClient provides an example of how to connect an incoming request span to an outgoing http call.

package main

import (
	"net/http"

	httptrace "github.com/DataDog/dd-trace-go/v2/contrib/net/http"
)

func main() {
	mux := httptrace.NewServeMux()
	// Note that `WrapClient` modifies the passed in Client, so all other users of DefaultClient in this example will have a traced http Client
	c := httptrace.WrapClient(http.DefaultClient)
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		req, _ := http.NewRequestWithContext(r.Context(), http.MethodGet, "http://test.test", nil)
		resp, err := c.Do(req)
		if err != nil {
			w.Write([]byte(err.Error()))
			return
		}
		defer resp.Body.Close()
		w.Write([]byte(resp.Status))
	})
	http.ListenAndServe(":8080", mux)
}
Output:

func WrapHandler

func WrapHandler(h http.Handler, service, resource string, opts ...Option) http.Handler

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 WrapRoundTripper

func WrapRoundTripper(rt http.RoundTripper, opts ...RoundTripperOption) http.RoundTripper

WrapRoundTripper returns a new RoundTripper which traces all requests sent over the transport.

Types

type HandlerOptionFn

type HandlerOptionFn func(*config)

HandlerOptionFn represents options applicable to NewServeMux and WrapHandler.

func NoDebugStack

func NoDebugStack() HandlerOptionFn

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.

func WithHeaderTags

func WithHeaderTags(headers []string) HandlerOptionFn

WithHeaderTags enables the integration to attach HTTP request headers as span tags. Warning: Using this feature can risk exposing sensitive data such as authorization tokens to Datadog. Special headers can not be sub-selected. E.g., an entire Cookie header would be transmitted, without the ability to choose specific Cookies.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option describes options for http.ServeMux.

type OptionFn

type OptionFn func(*commonConfig)

OptionFn represents options applicable to NewServeMux and WrapHandler.

func WithAnalytics

func WithAnalytics(on bool) OptionFn

WithAnalytics enables Trace Analytics for all started spans.

func WithAnalyticsRate

func WithAnalyticsRate(rate float64) OptionFn

WithAnalyticsRate sets the sampling rate for Trace Analytics events correlated to started spans.

func WithIgnoreRequest

func WithIgnoreRequest(f func(*http.Request) bool) OptionFn

WithIgnoreRequest holds the function to use for determining if the incoming HTTP request should not be traced.

func WithResourceNamer

func WithResourceNamer(namer func(req *http.Request) string) OptionFn

WithResourceNamer populates the name of a resource based on a custom function.

func WithService

func WithService(name string) OptionFn

WithService sets the given service name for the returned ServeMux.

func WithSpanOptions

func WithSpanOptions(opts ...tracer.StartSpanOption) OptionFn

WithSpanOptions defines a set of additional tracer.StartSpanOption to be added to spans started by the integration.

type RoundTripperAfterFunc

type RoundTripperAfterFunc func(*http.Response, *tracer.Span)

A RoundTripperAfterFunc can be used to modify a span after an http RoundTrip is made. It is possible for the http Response to be nil.

type RoundTripperBeforeFunc

type RoundTripperBeforeFunc func(*http.Request, *tracer.Span)

A RoundTripperBeforeFunc can be used to modify a span before an http RoundTrip is made.

type RoundTripperOption

type RoundTripperOption interface {
	// contains filtered or unexported methods
}

RoundTripperOption describes options for http.RoundTripper.

type RoundTripperOptionFn

type RoundTripperOptionFn func(*roundTripperConfig)

RoundTripperOptionFn represents options applicable to WrapClient and WrapRoundTripper.

func WithAfter

WithAfter adds a RoundTripperAfterFunc to the RoundTripper config.

func WithBefore

WithBefore adds a RoundTripperBeforeFunc to the RoundTripper config.

func WithErrorCheck

func WithErrorCheck(fn func(err error) bool) RoundTripperOptionFn

WithErrorCheck specifies a function fn which determines whether the passed error should be marked as an error. The fn is called whenever an http operation finishes with an error

func WithPropagation

func WithPropagation(propagation bool) RoundTripperOptionFn

WithPropagation enables/disables propagation for tracing headers. Disabling propagation will disconnect this trace from any downstream traces.

func WithSpanNamer

func WithSpanNamer(namer func(req *http.Request) string) RoundTripperOptionFn

WithSpanNamer specifies a function which will be used to obtain the span operation name for a given request.

type ServeConfig

type ServeConfig struct {
	// Service specifies the service name to use. If left blank, the global service name
	// will be inherited.
	Service string
	// Resource optionally specifies the resource name for this request.
	Resource string
	// QueryParams should be true in order to append the URL query values to the  "http.url" tag.
	QueryParams bool
	// Route is the request matched route if any, or is empty otherwise
	Route string
	// RouteParams specifies framework-specific route parameters (e.g. for route /user/:id coming
	// in as /user/123 we'll have {"id": "123"}). This field is optional and is used for monitoring
	// by AppSec. It is only taken into account when AppSec is enabled.
	RouteParams map[string]string
	// FinishOpts specifies any options to be used when finishing the request span.
	FinishOpts []tracer.FinishOption
	// SpanOpts specifies any options to be applied to the request starting span.
	SpanOpts []tracer.StartSpanOption
}

ServeConfig specifies the tracing configuration when using TraceAndServe.

type ServeMux

type ServeMux struct {
	*http.ServeMux
	// contains filtered or unexported fields
}

ServeMux is an HTTP request multiplexer that traces all the incoming requests.

func NewServeMux

func NewServeMux(opts ...Option) *ServeMux

NewServeMux allocates and returns an http.ServeMux augmented with the global tracer.

func (*ServeMux) ServeHTTP

func (mux *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL. We only need to rewrite this function to be able to trace all the incoming requests to the underlying multiplexer

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL