Skip to content

Commit

Permalink
reuse main http client + resolved memory leak (close previous respons…
Browse files Browse the repository at this point in the history
…e) before creating new one.
  • Loading branch information
cedricve committed Jan 16, 2025
1 parent ee8a919 commit 6fc6d9a
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
6 changes: 4 additions & 2 deletions Device.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ func (dev Device) callMethodDo(endpoint string, method interface{}) (*http.Respo

servResp, err := networking.SendSoap(dev.params.HttpClient, endpoint, soap.String())
if err != nil {
servResp, err = networking.SendSoapWithDigest(new(http.Client), endpoint, soap.String(), dev.params.Username, dev.params.Password)
servResp, err = networking.SendSoapWithDigest(dev.params.HttpClient, endpoint, soap.String(), dev.params.Username, dev.params.Password)
}

return servResp, err
Expand Down Expand Up @@ -344,7 +344,9 @@ func (dev Device) SendSoap(endpoint string, xmlRequestBody string) (*http.Respon

servResp, err := networking.SendSoap(dev.params.HttpClient, endpoint, soap.String())
if err != nil {
servResp, err = networking.SendSoapWithDigest(new(http.Client), endpoint, soap.String(), dev.params.Username, dev.params.Password)
// Close server response body to reuse the connection
servResp.Body.Close()
servResp, err = networking.SendSoapWithDigest(dev.params.HttpClient, endpoint, soap.String(), dev.params.Username, dev.params.Password)
}

return servResp, err
Expand Down
4 changes: 3 additions & 1 deletion networking/networking.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ func SendSoapWithDigest(httpClient *http.Client, endpoint, message, username, pa
req.Header.Set("Content-Type", "application/soap+xml; charset=utf-8")
resp, err := httpClient.Do(req)
if err != nil {
fmt.Println(err)
return resp, errors.Annotate(err, "Post with digest")
}

Expand All @@ -75,6 +74,9 @@ func SendSoapWithDigest(httpClient *http.Client, endpoint, message, username, pa
return resp, fmt.Errorf("fail to build digest: %w", err)
}

// Readout body to close the connection
resp.Body.Close()

req.Header.Add("Authorization", cred.String())
req.Body = io.NopCloser((bytes.NewBufferString(message)))
resp, err = httpClient.Do(req)
Expand Down

0 comments on commit 6fc6d9a

Please sign in to comment.