Skip to content

Instantly share code, notes, and snippets.

@nmccready
Created June 7, 2025 14:26
Show Gist options
  • Select an option

  • Save nmccready/f673c59de8d8a50d86f02becd7f70d4d to your computer and use it in GitHub Desktop.

Select an option

Save nmccready/f673c59de8d8a50d86f02becd7f70d4d to your computer and use it in GitHub Desktop.
Go laying round tripper HTTP logging
package main
import (
"bytes"
"io"
"log"
"net/http"
"net/http/httputil" // For Dumps
)
type debugRoundTripper struct {
proxiedTransport http.RoundTripper
}
func (drt *debugRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
// Dump request
reqDump, err := httputil.DumpRequestOut(req, true)
if err != nil {
log.Printf("Error dumping request: %v", err)
} else {
log.Printf("--- Request Dump ---\n%s\n--------------------", reqDump)
}
resp, err := drt.proxiedTransport.RoundTrip(req)
if err != nil {
log.Printf("Error during roundtrip: %v", err)
return resp, err
}
// Dump response
respDump, err := httputil.DumpResponse(resp, true)
if err != nil {
log.Printf("Error dumping response: %v", err)
} else {
log.Printf("--- Response Dump ---\n%s\n--------------------", respDump)
}
// If you want to log the response body but still return it,
// you'll need to read it into a buffer and then create a new io.ReadCloser
if resp.Body != nil {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("Error reading response body for dump: %v", err)
} else {
log.Printf("--- Response Body ---\n%s\n---------------------", bodyBytes)
}
resp.Body = io.NopCloser(bytes.NewBuffer(bodyBytes)) // Restore body for further reading
}
return resp, nil
}
// Use it like this:
// client := &http.Client{
// Transport: &debugRoundTripper{
// proxiedTransport: &http.Transport{
// Proxy: http.ProxyFromEnvironment, // Or http.ProxyURL(...)
// // ... other transport settings
// },
// },
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment