|
5 | 5 | "fmt"
|
6 | 6 | "log"
|
7 | 7 |
|
8 |
| - "io/ioutil" |
9 | 8 | "net/http"
|
10 | 9 | "net/url"
|
11 | 10 | "strconv"
|
@@ -151,7 +150,7 @@ func (c *Client) SetApiBaseURL(urlStr string) {
|
151 | 150 | c.apiBaseURL = urlStr
|
152 | 151 | }
|
153 | 152 |
|
154 |
| -func (c *Client) executeRaw(method string, urlStr string, text string) ([]byte, error) { |
| 153 | +func (c *Client) executeRaw(method string, urlStr string, text string) (io.ReadCloser, error) { |
155 | 154 | body := strings.NewReader(text)
|
156 | 155 |
|
157 | 156 | req, err := http.NewRequest(method, urlStr, body)
|
@@ -301,43 +300,43 @@ func (c *Client) authenticateRequest(req *http.Request) {
|
301 | 300 | }
|
302 | 301 |
|
303 | 302 | func (c *Client) doRequest(req *http.Request, emptyResponse bool) (interface{}, error) {
|
304 |
| - resBodyBytes, err := c.doRawRequest(req, emptyResponse) |
| 303 | + resBody, err := c.doRawRequest(req, emptyResponse) |
305 | 304 | if err != nil {
|
306 | 305 | return nil, err
|
307 | 306 | }
|
| 307 | + defer resBody.Close() |
308 | 308 |
|
309 | 309 | var result interface{}
|
310 |
| - err = json.Unmarshal(resBodyBytes, &result) |
311 |
| - if err != nil { |
| 310 | + if err := json.NewDecoder(resBody).Decode(&result); err != nil { |
312 | 311 | log.Println("Could not unmarshal JSON payload, returning raw response")
|
313 |
| - return resBodyBytes, err |
| 312 | + return resBody, err |
314 | 313 | }
|
315 | 314 |
|
316 | 315 | return result, nil
|
317 | 316 | }
|
318 | 317 |
|
319 |
| -func (c *Client) doRawRequest(req *http.Request, emptyResponse bool) ([]byte, error) { |
| 318 | +func (c *Client) doRawRequest(req *http.Request, emptyResponse bool) (io.ReadCloser, error) { |
320 | 319 | resp, err := c.HttpClient.Do(req)
|
321 | 320 | if err != nil {
|
322 | 321 | return nil, err
|
323 | 322 | }
|
324 |
| - if resp.Body != nil { |
325 |
| - defer resp.Body.Close() |
326 |
| - } |
327 | 323 |
|
328 | 324 | if (resp.StatusCode != http.StatusOK) && (resp.StatusCode != http.StatusCreated) {
|
| 325 | + resp.Body.Close() |
329 | 326 | return nil, fmt.Errorf(resp.Status)
|
330 | 327 | }
|
331 | 328 |
|
332 | 329 | if emptyResponse {
|
| 330 | + resp.Body.Close() |
333 | 331 | return nil, nil
|
334 | 332 | }
|
335 | 333 |
|
336 | 334 | if resp.Body == nil {
|
| 335 | + resp.Body.Close() |
337 | 336 | return nil, fmt.Errorf("response body is nil")
|
338 | 337 | }
|
339 | 338 |
|
340 |
| - return ioutil.ReadAll(resp.Body) |
| 339 | + return resp.Body, nil |
341 | 340 | }
|
342 | 341 |
|
343 | 342 | func (c *Client) requestUrl(template string, args ...interface{}) string {
|
|
0 commit comments