Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix leak & refactor #211

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 21 additions & 8 deletions gorequest.go
Original file line number Diff line number Diff line change
Expand Up @@ -1101,30 +1101,43 @@ func (s *SuperAgent) getResponseBytes() (Response, []byte, []error) {
}

// Send request
resp, err = s.Client.Do(req)
resp, body, err := s.sendRequest(req)
if err != nil {
s.Errors = append(s.Errors, err)
return nil, nil, s.Errors
}
defer resp.Body.Close()

return resp, body, nil
}

// sendRequest executes request, returns all bytes & response or error.
func (s *SuperAgent) sendRequest(req *http.Request) (Response, []byte, error) {
resp, err := s.Client.Do(req)
if err != nil {
return nil, nil, err
}

// Log details of this response
if s.Debug {
dump, err := httputil.DumpResponse(resp, true)
var dump []byte
dump, err = httputil.DumpResponse(resp, true)
if nil != err {
s.logger.Println("Error:", err)
} else {
s.logger.Printf("HTTP Response: %s", string(dump))
}
}

// ReadAll doesn't close in itself, so immediately closing here to prevent leaking.
body, err := ioutil.ReadAll(resp.Body)
// Reset resp.Body so it can be use again
resp.Body.Close()

// Creates a buffer on top of the returned []byte, so resp.Body can be used again.
// Any changes made to 'body' bytes will be reflected in this buffer.
// In the case of a partial read, the partial data will be there.
resp.Body = ioutil.NopCloser(bytes.NewBuffer(body))
if err != nil {
return nil, nil, []error{err}
}
return resp, body, nil

return resp, body, err
}

func (s *SuperAgent) MakeRequest() (*http.Request, error) {
Expand Down