added gzip decompression of response body
This commit is contained in:
+24
-8
@@ -2,6 +2,7 @@ package reddit
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -372,15 +373,30 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Res
|
||||
c.rateMu.Unlock()
|
||||
|
||||
err = CheckResponse(resp)
|
||||
if err != nil {
|
||||
if err != nil || v == nil {
|
||||
return response, err
|
||||
}
|
||||
|
||||
if v != nil {
|
||||
if w, ok := v.(io.Writer); ok {
|
||||
_, err = io.Copy(w, response.Body)
|
||||
w, ok := v.(io.Writer)
|
||||
if ok {
|
||||
_, err = io.Copy(w, response.Body)
|
||||
if err != nil {
|
||||
return response, err
|
||||
}
|
||||
} else {
|
||||
if response.Header.Get("Content-Encoding") == "gzip" {
|
||||
gzipReader, err := gzip.NewReader(resp.Body)
|
||||
if err != nil {
|
||||
return response, err
|
||||
return response, fmt.Errorf("Error creating gzip reader: %s", err)
|
||||
}
|
||||
defer gzipReader.Close()
|
||||
b, err := io.ReadAll(gzipReader)
|
||||
if err != nil {
|
||||
return response, fmt.Errorf("Error decoding gzip json: %s", err)
|
||||
}
|
||||
err = json.Unmarshal(b, v)
|
||||
if err != nil {
|
||||
return response, fmt.Errorf("Error unmarshalling json: %s", err)
|
||||
}
|
||||
} else {
|
||||
err = json.NewDecoder(response.Body).Decode(v)
|
||||
@@ -388,10 +404,10 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Res
|
||||
return response, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if anchor, ok := v.(anchor); ok {
|
||||
response.populateAnchors(anchor)
|
||||
}
|
||||
if anchor, ok := v.(anchor); ok {
|
||||
response.populateAnchors(anchor)
|
||||
}
|
||||
|
||||
return response, nil
|
||||
|
||||
Reference in New Issue
Block a user