From 6e389591f13c321a7f5f3e0c65ec21810cd8a3ea Mon Sep 17 00:00:00 2001 From: roc Date: Sun, 14 Aug 2022 15:48:27 +0800 Subject: [PATCH] Restore Response.Body when AutoReadResponse is enabled(#152) --- client.go | 3 +++ request_test.go | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/client.go b/client.go index 6de39af9..bd56526c 100644 --- a/client.go +++ b/client.go @@ -1,6 +1,7 @@ package req import ( + "bytes" "context" "crypto/tls" "crypto/x509" @@ -1191,6 +1192,8 @@ func (c *Client) roundTrip(r *Request) (resp *Response, err error) { if err != nil { return } + // restore body for re-reads + resp.Body = ioutil.NopCloser(bytes.NewReader(resp.body)) } for _, f := range r.client.afterResponse { diff --git a/request_test.go b/request_test.go index 624c6f47..76ddbb8c 100644 --- a/request_test.go +++ b/request_test.go @@ -1010,3 +1010,14 @@ func TestDownloadCallback(t *testing.T) { assertSuccess(t, resp, err) tests.AssertEqual(t, true, n > 0) } + +func TestRestoreResponseBody(t *testing.T) { + c := tc() + resp, err := c.R().Get("/") + assertSuccess(t, resp, err) + tests.AssertNoError(t, err) + tests.AssertEqual(t, true, len(resp.Bytes()) > 0) + body, err := ioutil.ReadAll(resp.Body) + tests.AssertNoError(t, err) + tests.AssertEqual(t, true, len(body) > 0) +}