github.com/mier85/go-sensor@v1.30.1-0.20220920111756-9bf41b3bc7e0/example_instrumentation_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 "net/http" 9 10 instana "github.com/mier85/go-sensor" 11 ) 12 13 // This example demonstrates how to instrument an HTTP handler with Instana and register it 14 // in http.DefaultServeMux 15 func ExampleTracingHandlerFunc() { 16 // Here we initialize a new instance of instana.Sensor, however it is STRONGLY recommended 17 // to use a single instance throughout your application 18 sensor := instana.NewSensor("my-http-server") 19 20 http.HandleFunc("/", instana.TracingNamedHandlerFunc(sensor, "root", "/", func(w http.ResponseWriter, req *http.Request) { 21 // handler code 22 })) 23 } 24 25 // This example demonstrates how to instrument an HTTP client with Instana 26 func ExampleRoundTripper() { 27 // Here we initialize a new instance of instana.Sensor, however it is STRONGLY recommended 28 // to use a single instance throughout your application 29 sensor := instana.NewSensor("my-http-client") 30 span := sensor.Tracer().StartSpan("entry") 31 32 // http.DefaultTransport is used as a default RoundTripper, however you can provide 33 // your own implementation 34 client := &http.Client{ 35 Transport: instana.RoundTripper(sensor, nil), 36 } 37 38 // Inject parent span into the request context 39 ctx := instana.ContextWithSpan(context.Background(), span) 40 req, _ := http.NewRequest("GET", "https://www.instana.com", nil) 41 42 // Execute request as usual 43 client.Do(req.WithContext(ctx)) 44 } 45 46 // This example demonstrates how to instrument an *sql.DB instance created with sql.Open() 47 func ExampleSQLOpen() { 48 // Here we initialize a new instance of instana.Sensor, however it is STRONGLY recommended 49 // to use a single instance throughout your application 50 sensor := instana.NewSensor("my-http-client") 51 52 // Instrument the driver. Normally this would be a type provided by the driver library, e.g. 53 // pq.Driver{} or mysql.Driver{}, but here we use a test mock to avoid bringing external dependencies 54 instana.InstrumentSQLDriver(sensor, "your_db_driver", sqlDriver{}) 55 56 // Replace sql.Open() with instana.SQLOpen() 57 db, _ := instana.SQLOpen("your_db_driver", "driver connection string") 58 59 // Inject parent span into the context 60 span := sensor.Tracer().StartSpan("entry") 61 ctx := instana.ContextWithSpan(context.Background(), span) 62 63 // Query the database, passing the context containing the active span 64 db.QueryContext(ctx, "SELECT * FROM users;") 65 66 // SQL queries that are not expected to return a result set are also supported 67 db.ExecContext(ctx, "UPDATE users SET last_seen_at = NOW();") 68 }