Ensure response body gets closed (#3409)

From https://pkg.go.dev/net/http#Client.Do

> If the returned error is nil, the Response will contain a non-nil
> Body which the user is expected to close. If the Body is not both read
> to EOF and closed, the Client's underlying RoundTripper (typically
> Transport) may not be able to re-use a persistent TCP connection to
> the server for a subsequent "keep-alive" request.

These were found using https://github.com/timakin/bodyclose. Not adding it as a linter for now as it was producing false positive(I think) on OneDrive item. The close was happening in a9918d2f78/src/internal/kopia/upload.go (L68) instead of right alongside it which might be why it got thrown off.

<!-- PR description-->

---

#### Does this PR need a docs update or release note?

- [ ]  Yes, it's included
- [ ] 🕐 Yes, but in a later PR
- [x]  No

#### Type of change

<!--- Please check the type of change your PR introduces: --->
- [ ] 🌻 Feature
- [x] 🐛 Bugfix
- [ ] 🗺️ Documentation
- [ ] 🤖 Supportability/Tests
- [ ] 💻 CI/Deployment
- [ ] 🧹 Tech Debt/Cleanup

#### Issue(s)

<!-- Can reference multiple issues. Use one of the following "magic words" - "closes, fixes" to auto-close the Github issue. -->
* #<issue>

#### Test Plan

<!-- How will this be tested prior to merging.-->
- [x] 💪 Manual
- [ ]  Unit test
- [ ] 💚 E2E
This commit is contained in:
Abin Simon 2023-05-16 10:16:56 +05:30 committed by GitHub
parent 1961104207
commit a55758020f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 10 additions and 2 deletions

View File

@ -198,6 +198,7 @@ func getDriveItemContent(
if err != nil {
return nil, clues.New("downloading item").With("error", err)
}
defer resp.Body.Close()
content, err := io.ReadAll(resp.Body)
if err != nil {

View File

@ -62,6 +62,9 @@ func (suite *ConcurrencyLimiterUnitTestSuite) TestConcurrencyLimiter() {
resp, err := client.Get(ts.URL)
require.NoError(t, err)
defer resp.Body.Close()
assert.Equal(t, http.StatusOK, resp.StatusCode)
}()
}

View File

@ -40,8 +40,10 @@ func (suite *HTTPWrapperIntgSuite) TestNewHTTPWrapper() {
"https://www.corsobackup.io",
nil,
nil)
require.NoError(t, err, clues.ToCore(err))
defer resp.Body.Close()
require.NotNil(t, resp)
require.Equal(t, http.StatusOK, resp.StatusCode)
}
@ -108,8 +110,10 @@ func (suite *HTTPWrapperUnitSuite) TestNewHTTPWrapper_redirectMiddleware() {
hw := NewHTTPWrapper(appendMiddleware(&mwResp))
resp, err := hw.Request(ctx, http.MethodGet, url, nil, nil)
require.NoError(t, err, clues.ToCore(err))
defer resp.Body.Close()
require.NotNil(t, resp)
// require.Equal(t, 1, calledCorrectly, "test server was called with expected path")
require.Equal(t, http.StatusOK, resp.StatusCode)