Skip to content

Instantly share code, notes, and snippets.

@velp
Created February 11, 2021 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velp/73b5efb64174d960a45bcf812098f8d4 to your computer and use it in GitHub Desktop.
Save velp/73b5efb64174d960a45bcf812098f8d4 to your computer and use it in GitHub Desktop.
Go HTTP client debug requests/responses

Add logging round tripper:

import (
	"fmt"
	"net/http"
	"net/http/httputil"
)

// This type implements the http.RoundTripper interface.
type LoggingRoundTripper struct {
	Proxied http.RoundTripper
}

func (lrt LoggingRoundTripper) RoundTrip(req *http.Request) (res *http.Response, err error) {
	// Log request
	dumpReq, err := httputil.DumpRequest(req, true)
	if err != nil {
		fmt.Printf("ERROR dumping request: %v", err)

		return
	}

	fmt.Printf("REQUEST:\n%s\n", dumpReq)

	// Send the request, get the response (or the error)
	res, err = lrt.Proxied.RoundTrip(req)
	if err != nil {
		fmt.Printf("ERROR: %v", err)

		return
	}

	// Log response
	dumpResp, err := httputil.DumpResponse(res, true)
	if err != nil {
		fmt.Printf("ERROR dumping response: %v", err)

		return
	}

	fmt.Printf("RESULT:\n%s\n", dumpResp)

	return
}

And then you can use it like:

httpClient := &http.Client{Transport: LoggingRoundTripper{http.DefaultTransport}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment