Fix memory leaks due to not closing http request body (#997)
This commit is contained in:
parent
4828d197d6
commit
62052e0159
5 changed files with 32 additions and 28 deletions
|
|
@ -1,8 +1,6 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
|
@ -67,9 +65,6 @@ func ReadBody(resp *http.Response) ([]byte, error) {
|
|||
return []byte{}, err
|
||||
}
|
||||
|
||||
// maintain body after reading
|
||||
resp.Body = io.NopCloser(bytes.NewBuffer(b))
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return b, StatusError{resp: resp}
|
||||
}
|
||||
|
|
@ -77,15 +72,6 @@ func ReadBody(resp *http.Response) ([]byte, error) {
|
|||
return b, nil
|
||||
}
|
||||
|
||||
// DecodeJSON reads HTTP response and decodes JSON body if error is nil
|
||||
func DecodeJSON(resp *http.Response, res interface{}) error {
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return StatusError{resp: resp}
|
||||
}
|
||||
|
||||
return json.NewDecoder(resp.Body).Decode(&res)
|
||||
}
|
||||
|
||||
// New builds and executes HTTP request and returns the response
|
||||
func New(method, uri string, data io.Reader, headers ...map[string]string) (*http.Request, error) {
|
||||
req, err := http.NewRequest(method, uri, data)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package request
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
|
|
@ -47,20 +48,31 @@ func (r *Helper) GetBody(url string) ([]byte, error) {
|
|||
return body, err
|
||||
}
|
||||
|
||||
// DoJSON executes HTTP request and decodes JSON response
|
||||
// decodeJSON reads HTTP response and decodes JSON body if error is nil
|
||||
func decodeJSON(resp *http.Response, res interface{}) error {
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return StatusError{resp: resp}
|
||||
}
|
||||
|
||||
return json.NewDecoder(resp.Body).Decode(&res)
|
||||
}
|
||||
|
||||
// DoJSON executes HTTP request and decodes JSON response. It returns a StatusError on response codes other than HTTP 2xx.
|
||||
func (r *Helper) DoJSON(req *http.Request, res interface{}) error {
|
||||
resp, err := r.Do(req)
|
||||
if err == nil {
|
||||
err = DecodeJSON(resp, &res)
|
||||
defer resp.Body.Close()
|
||||
err = decodeJSON(resp, &res)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// GetJSON executes HTTP GET request and decodes JSON response
|
||||
// GetJSON executes HTTP GET request and decodes JSON response. It returns a StatusError on response codes other than HTTP 2xx.
|
||||
func (r *Helper) GetJSON(url string, res interface{}) error {
|
||||
resp, err := r.Get(url)
|
||||
if err == nil {
|
||||
err = DecodeJSON(resp, &res)
|
||||
defer resp.Body.Close()
|
||||
err = decodeJSON(resp, &res)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue