gitlab.com/gitlab-org/labkit@v1.21.0/example/router.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "io" 6 "log" 7 "net/http" 8 "strconv" 9 "time" 10 11 "gitlab.com/gitlab-org/labkit/correlation" 12 "gitlab.com/gitlab-org/labkit/tracing" 13 tracingcorrelation "gitlab.com/gitlab-org/labkit/tracing/correlation" 14 ) 15 16 func main() { 17 tracing.Initialize(tracing.WithServiceName("router")) 18 19 tr := &http.Transport{ 20 MaxIdleConns: 10, 21 IdleConnTimeout: 30 * time.Second, 22 DisableCompression: true, 23 } 24 25 client := &http.Client{ 26 Transport: correlation.NewInstrumentedRoundTripper(tracing.NewRoundTripper(tr)), 27 } 28 29 // Listen and propagate traces 30 http.Handle("/query", 31 // Add the tracing middleware in 32 correlation.InjectCorrelationID( 33 tracing.Handler( 34 tracingcorrelation.BaggageHandler( 35 36 http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 37 query := r.URL.Query() 38 ttlString := query.Get("ttl") 39 var ttl int 40 var err error 41 42 if ttlString == "" { 43 ttl = 1 44 } else { 45 ttl, err = strconv.Atoi(ttlString) 46 if err != nil { 47 ttl = 1 48 } 49 } 50 51 ttl-- 52 if ttl < 0 { 53 fmt.Fprintf(w, "Hello") 54 return 55 } 56 57 nextURL := fmt.Sprintf("http://localhost:8080/query?ttl=%d", ttl) 58 req, err := http.NewRequest(http.MethodGet, nextURL, nil) 59 if err != nil { 60 w.WriteHeader(500) 61 return 62 } 63 64 req = req.WithContext(r.Context()) 65 66 resp, err := client.Do(req) 67 if err != nil { 68 w.WriteHeader(500) 69 return 70 } 71 defer resp.Body.Close() 72 73 _, err = io.Copy(w, resp.Body) 74 if err != nil { 75 w.WriteHeader(500) 76 return 77 } 78 })), 79 // Use this route identifier with the tracing middleware 80 tracing.WithRouteIdentifier("/query"), 81 ), 82 correlation.WithPropagation())) 83 84 log.Fatal(http.ListenAndServe(":8080", nil)) 85 }