Created
August 2, 2021 23:15
-
-
Save aojea/aa45bcb6b9adf89c64b8cc874140dac8 to your computer and use it in GitHub Desktop.
transport wrapper to trace http requests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"fmt" | |
"log" | |
"net/http" | |
"net/http/httptrace" | |
) | |
// transport is an http.RoundTripper that keeps track of the in-flight | |
// request and implements hooks to report HTTP tracing events. | |
type transport struct { | |
} | |
// RoundTrip wraps http.DefaultTransport.RoundTrip to keep track | |
// of the current request. | |
func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) { | |
trace := &httptrace.ClientTrace{ | |
DNSDone: func(dnsInfo httptrace.DNSDoneInfo) { | |
fmt.Printf("DNS Info: %+v\n", dnsInfo) | |
}, | |
GotConn: func(connInfo httptrace.GotConnInfo) { | |
fmt.Printf("Got Conn: %+v\n", connInfo) | |
}, | |
} | |
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace)) | |
return http.DefaultTransport.RoundTrip(req) | |
} | |
func main() { | |
t := &transport{} | |
req, _ := http.NewRequest("GET", "https://google.com", nil) | |
client := &http.Client{Transport: t} | |
if _, err := client.Do(req); err != nil { | |
log.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment