diff --git a/client.go b/client.go index c5080378..a10a5200 100644 --- a/client.go +++ b/client.go @@ -801,7 +801,7 @@ func (c *Client) execute(req *Request) (*Response, error) { body := resp.Body // GitHub #142 - if strings.EqualFold(resp.Header.Get(hdrContentEncodingKey), "gzip") { + if strings.EqualFold(resp.Header.Get(hdrContentEncodingKey), "gzip") && resp.ContentLength > 0 { if _, ok := body.(*gzip.Reader); !ok { body, err = gzip.NewReader(body) if err != nil { diff --git a/client_test.go b/client_test.go index 78f4d0e0..be7ea0d2 100644 --- a/client_test.go +++ b/client_test.go @@ -479,16 +479,22 @@ func TestAutoGzip(t *testing.T) { defer ts.Close() c := New() + testcases := []struct{ url, want string }{ + {ts.URL + "/gzip-test", "This is Gzip response testing"}, + {ts.URL + "/gzip-test-gziped-empty-body", ""}, + {ts.URL + "/gzip-test-no-gziped-body", ""}, + } + for _, tc := range testcases { + resp, err := c.R(). + SetHeader("Accept-Encoding", "gzip"). + Get(tc.url) - resp, err := c.R(). - SetHeader("Accept-Encoding", "gzip"). - Get(ts.URL + "/gzip-test") - - assertError(t, err) - assertEqual(t, http.StatusOK, resp.StatusCode()) - assertEqual(t, "200 OK", resp.Status()) - assertNotNil(t, resp.Body()) - assertEqual(t, "This is Gzip response testing", resp.String()) + assertError(t, err) + assertEqual(t, http.StatusOK, resp.StatusCode()) + assertEqual(t, "200 OK", resp.Status()) + assertNotNil(t, resp.Body()) + assertEqual(t, tc.want, resp.String()) - logResponse(t, resp) + logResponse(t, resp) + } } diff --git a/resty_test.go b/resty_test.go index 801148d0..9a201606 100644 --- a/resty_test.go +++ b/resty_test.go @@ -450,7 +450,19 @@ func createGenServer(t *testing.T) *httptest.Server { zw := gzip.NewWriter(w) zw.Write([]byte("This is Gzip response testing")) zw.Close() + } else if r.URL.Path == "/gzip-test-gziped-empty-body" { + w.Header().Set(hdrContentTypeKey, plainTextType) + w.Header().Set(hdrContentEncodingKey, "gzip") + zw := gzip.NewWriter(w) + // write gziped empty body + zw.Write([]byte("")) + zw.Close() + } else if r.URL.Path == "/gzip-test-no-gziped-body" { + w.Header().Set(hdrContentTypeKey, plainTextType) + w.Header().Set(hdrContentEncodingKey, "gzip") + // don't write body } + return }