github.com/newrelic/go-agent@v3.26.0+incompatible/examples/client-round-tripper/main.go (about) 1 // Copyright 2020 New Relic Corporation. All rights reserved. 2 // SPDX-License-Identifier: Apache-2.0 3 4 // An application that illustrates Distributed Tracing or Cross Application 5 // Tracing when using NewRoundTripper. 6 package main 7 8 import ( 9 "fmt" 10 "net/http" 11 "os" 12 "time" 13 14 "github.com/newrelic/go-agent" 15 ) 16 17 func mustGetEnv(key string) string { 18 if val := os.Getenv(key); "" != val { 19 return val 20 } 21 panic(fmt.Sprintf("environment variable %s unset", key)) 22 } 23 24 func doRequest(txn newrelic.Transaction) error { 25 for _, addr := range []string{"segments", "mysql"} { 26 url := fmt.Sprintf("http://localhost:8000/%s", addr) 27 req, err := http.NewRequest("GET", url, nil) 28 if nil != err { 29 return err 30 } 31 client := &http.Client{} 32 33 // Using NewRoundTripper automatically instruments all request 34 // for Distributed Tracing and Cross Application Tracing. 35 client.Transport = newrelic.NewRoundTripper(txn, nil) 36 37 resp, err := client.Do(req) 38 if nil != err { 39 return err 40 } 41 fmt.Println("response code is", resp.StatusCode) 42 } 43 return nil 44 } 45 46 func main() { 47 cfg := newrelic.NewConfig("Client App RoundTripper", mustGetEnv("NEW_RELIC_LICENSE_KEY")) 48 cfg.Logger = newrelic.NewDebugLogger(os.Stdout) 49 cfg.DistributedTracer.Enabled = true 50 app, err := newrelic.NewApplication(cfg) 51 if nil != err { 52 fmt.Println(err) 53 os.Exit(1) 54 } 55 56 // Wait for the application to connect. 57 if err = app.WaitForConnection(5 * time.Second); nil != err { 58 fmt.Println(err) 59 } 60 61 txn := app.StartTransaction("client-txn", nil, nil) 62 err = doRequest(txn) 63 if nil != err { 64 txn.NoticeError(err) 65 } 66 txn.End() 67 68 // Shut down the application to flush data to New Relic. 69 app.Shutdown(10 * time.Second) 70 }