Skip to content

Instantly share code, notes, and snippets.

@johnweldon johnweldon/debug.go
Created Apr 26, 2016

Embed
What would you like to do?
Useful http debugging file. Replaces http.DefaultTransport with a logger of all http traffic.
package main
import (
"fmt"
"io"
"net/http"
"net/http/httputil"
"os"
)
func init() {
http.DefaultTransport = wrapRoundTripper(http.DefaultTransport, os.Stdout)
}
func wrapRoundTripper(in http.RoundTripper, log io.Writer) http.RoundTripper {
return &loggingRoundTripper{inner: in, logger: log}
}
type loggingRoundTripper struct {
inner http.RoundTripper
logger io.Writer
}
func (d *loggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
d.dumpRequest(req)
res, err := d.inner.RoundTrip(req)
d.dumpResponse(res)
return res, err
}
func (d *loggingRoundTripper) dumpRequest(r *http.Request) {
dump, err := httputil.DumpRequestOut(r, true)
if err != nil {
fmt.Fprintf(d.logger, "\n\tERROR dumping: %v\n", err)
}
d.dump("REQUEST", dump)
}
func (d *loggingRoundTripper) dumpResponse(r *http.Response) {
dump, err := httputil.DumpResponse(r, true)
if err != nil {
fmt.Fprintf(d.logger, "\n\tERROR dumping: %v\n", err)
}
d.dump("RESPONSE", dump)
}
func (d *loggingRoundTripper) dump(label string, dump []byte) {
fmt.Fprintf(d.logger, "\n------------------------------------------------------------\n")
defer fmt.Fprintf(d.logger, "\n------------------------------------------------------------\n")
fmt.Fprintf(d.logger, "%s:\n--\n%s", label, string(dump))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.