golang.org/toolchain@v0.0.1-go1.9rc2.windows-amd64/blog/content/http-tracing/client.go (about) 1 // +build OMIT 2 3 package main 4 5 import ( 6 "fmt" 7 "log" 8 "net/http" 9 "net/http/httptrace" 10 ) 11 12 // transport is an http.RoundTripper that keeps track of the in-flight 13 // request and implements hooks to report HTTP tracing events. 14 type transport struct { 15 current *http.Request 16 } 17 18 // RoundTrip wraps http.DefaultTransport.RoundTrip to keep track 19 // of the current request. 20 func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) { 21 t.current = req 22 return http.DefaultTransport.RoundTrip(req) 23 } 24 25 // GotConn prints whether the connection has been used previously 26 // for the current request. 27 func (t *transport) GotConn(info httptrace.GotConnInfo) { 28 fmt.Printf("Connection reused for %v? %v\n", t.current.URL, info.Reused) 29 } 30 31 func main() { 32 t := &transport{} 33 34 req, _ := http.NewRequest("GET", "https://google.com", nil) 35 trace := &httptrace.ClientTrace{ 36 GotConn: t.GotConn, 37 } 38 req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) 39 40 client := &http.Client{Transport: t} 41 if _, err := client.Do(req); err != nil { 42 log.Fatal(err) 43 } 44 }