« Back to Index

[Golang Read HTTP Response Body TWICE!]

View original Gist on GitHub

Tags: #go #golang #http #response #body #read

Golang Read HTTP Response Body TWICE.go

// ReadBody reads the provided http.Response#Body and resets it to a type that
// would result in a additional read of the body to not trigger an error.
//
// this is to side-step the default behaviour, which for attempting to read a
// response body twice, is to error with: `http: read on closed response body`.
//
// the reason we have to do this is because when
// httputil.ReverseProxy#ModifyResponse returns an error, the internal
// implementation calls `r.Body.Close()` automatically before calling
// httputil.ReverseProxy#ErrorHandler.
//
// source code reference:
// https://github.com/golang/go/blob/18107ed9fbdb0d2ae1006857e21a8a66882e12dd/src/net/http/httputil/reverseproxy.go#L170
func ReadBody(r *http.Response) []byte {
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		body = []byte(http.StatusText(r.StatusCode))
	}

	r.Body.Close()
	r.Body = ioutil.NopCloser(bytes.NewBuffer(body))

	return body
}

// PROBABLY BETTER TO USE bytes.NewReader instead of bytes.NewBuffer