Skip to content

Instantly share code, notes, and snippets.

@aojea
Created August 2, 2021 23:15
Show Gist options
  • Save aojea/aa45bcb6b9adf89c64b8cc874140dac8 to your computer and use it in GitHub Desktop.
Save aojea/aa45bcb6b9adf89c64b8cc874140dac8 to your computer and use it in GitHub Desktop.
transport wrapper to trace http requests
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