github.com/weaveworks/common@v0.0.0-20230728070032-dd9e68f319d5/middleware/http_tracing.go (about)

     1  package middleware
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/opentracing-contrib/go-stdlib/nethttp"
     8  	"github.com/opentracing/opentracing-go"
     9  )
    10  
    11  // Dummy dependency to enforce that we have a nethttp version newer
    12  // than the one which implements Websockets. (No semver on nethttp)
    13  var _ = nethttp.MWURLTagFunc
    14  
    15  // Tracer is a middleware which traces incoming requests.
    16  type Tracer struct {
    17  	RouteMatcher RouteMatcher
    18  	SourceIPs    *SourceIPExtractor
    19  }
    20  
    21  // Wrap implements Interface
    22  func (t Tracer) Wrap(next http.Handler) http.Handler {
    23  	options := []nethttp.MWOption{
    24  		nethttp.OperationNameFunc(func(r *http.Request) string {
    25  			op := getRouteName(t.RouteMatcher, r)
    26  			if op == "" {
    27  				return "HTTP " + r.Method
    28  			}
    29  
    30  			return fmt.Sprintf("HTTP %s - %s", r.Method, op)
    31  		}),
    32  		nethttp.MWSpanObserver(func(sp opentracing.Span, r *http.Request) {
    33  			// add a tag with the client's user agent to the span
    34  			userAgent := r.Header.Get("User-Agent")
    35  			if userAgent != "" {
    36  				sp.SetTag("http.user_agent", userAgent)
    37  			}
    38  
    39  			// add a tag with the client's sourceIPs to the span, if a
    40  			// SourceIPExtractor is given.
    41  			if t.SourceIPs != nil {
    42  				sp.SetTag("sourceIPs", t.SourceIPs.Get(r))
    43  			}
    44  		}),
    45  	}
    46  
    47  	return nethttp.Middleware(opentracing.GlobalTracer(), next, options...)
    48  }