Last active
February 11, 2020 19:42
-
-
Save Integralist/0068812f12b4c72ee8e9d10ce38a1ed9 to your computer and use it in GitHub Desktop.
[Golang Read HTTP Response Body TWICE!] #go #golang #http #response #body #read
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment