github.com/mier85/go-sensor@v1.30.1-0.20220920111756-9bf41b3bc7e0/example_httpclient_test.go (about)

     1  // (c) Copyright IBM Corp. 2021
     2  // (c) Copyright Instana Inc. 2020
     3  
     4  package instana_test
     5  
     6  import (
     7  	"context"
     8  	"log"
     9  	"net/http"
    10  
    11  	instana "github.com/mier85/go-sensor"
    12  	"github.com/opentracing/opentracing-go/ext"
    13  )
    14  
    15  // This example shows how to instrument an HTTP client with Instana tracing
    16  func Example_roundTripper() {
    17  	sensor := instana.NewSensor("my-http-client")
    18  
    19  	// Wrap the original http.Client transport with instana.RoundTripper().
    20  	// The http.DefaultTransport will be used if there was no transport provided.
    21  	client := &http.Client{
    22  		Transport: instana.RoundTripper(sensor, nil),
    23  	}
    24  
    25  	// The call should always start with an entry span (https://docs.instana.io/quick_start/custom_tracing/#always-start-new-traces-with-entry-spans)
    26  	// Normally this would be your HTTP/GRPC/message queue request span, but here we need to
    27  	// create it explicitly.
    28  	sp := sensor.Tracer().StartSpan("client-call")
    29  	sp.SetTag(string(ext.SpanKind), "entry")
    30  
    31  	req, err := http.NewRequest(http.MethodGet, "https://www.instana.com", nil)
    32  	if err != nil {
    33  		log.Fatalf("failed to create request: %s", err)
    34  	}
    35  
    36  	// Inject the parent span into request context
    37  	ctx := instana.ContextWithSpan(context.Background(), sp)
    38  
    39  	// Use your instrumented http.Client to propagate tracing context with the request
    40  	_, err = client.Do(req.WithContext(ctx))
    41  	if err != nil {
    42  		log.Fatalf("failed to GET https://www.instana.com: %s", err)
    43  	}
    44  }