github.com/instana/go-sensor@v1.62.2-0.20240520081010-4919868049e1/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/instana/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 col := instana.InitCollector(&instana.Options{ 18 Service: "my-http-client", 19 }) 20 21 // Wrap the original http.Client transport with instana.RoundTripper(). 22 // The http.DefaultTransport will be used if there was no transport provided. 23 client := &http.Client{ 24 Transport: instana.RoundTripper(col, nil), 25 } 26 27 // Every call should start with an entry span (https://www.ibm.com/docs/en/instana-observability/current?topic=tracing-best-practices#start-new-traces-with-entry-spans) 28 // Normally this would be your HTTP/GRPC/message queue request span, but here we need to create it explicitly, since an HTTP client call is 29 // an exit span. And all exit spans must have a parent entry span. 30 sp := col.Tracer().StartSpan("client-call") 31 sp.SetTag(string(ext.SpanKind), "entry") 32 33 req, err := http.NewRequest(http.MethodGet, "https://www.instana.com", nil) 34 if err != nil { 35 log.Fatalf("failed to create request: %s", err) 36 } 37 38 // Inject the parent span into request context 39 ctx := instana.ContextWithSpan(context.Background(), sp) 40 41 // Use your instrumented http.Client to propagate tracing context with the request 42 _, err = client.Do(req.WithContext(ctx)) 43 if err != nil { 44 log.Fatalf("failed to GET https://www.instana.com: %s", err) 45 } 46 47 // Remember to always finish spans that were created manually to make sure it's propagated to the Agent. 48 // In this case, we want to make sure that the entry span is finished after the HTTP request is completed. 49 // Optionally, we could use defer right after the span is created. 50 sp.Finish() 51 }