From a2279ed90b953f8925d16fe1df297dced12c3ba3 Mon Sep 17 00:00:00 2001 From: Michael Hanselmann Date: Fri, 5 Jan 2024 23:50:20 +0100 Subject: [PATCH] Avoid panic when download request fails at connection stage `RawBody()` may return nil if the connection failed (e.g. connection refused). --- pkg/client/download.go | 4 ++-- pkg/client/download_test.go | 9 +++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/pkg/client/download.go b/pkg/client/download.go index 18b9e2c..bb37f95 100644 --- a/pkg/client/download.go +++ b/pkg/client/download.go @@ -30,8 +30,8 @@ func (c *Client) download(ctx context.Context, w io.Writer, url string, expectDi resp, err := req.Get(url) - if resp != nil { - defer multierr.AppendInvoke(&err, multierr.Close(resp.RawBody())) + if !(resp == nil || resp.RawBody() == nil) { + defer multierr.AppendFunc(&err, resp.RawBody().Close) } if err := convertError(err, resp); err != nil { diff --git a/pkg/client/download_test.go b/pkg/client/download_test.go index c7bea40..0e61b1b 100644 --- a/pkg/client/download_test.go +++ b/pkg/client/download_test.go @@ -51,6 +51,15 @@ func TestDownload(t *testing.T) { Message: `418`, }, }, + { + name: "connection error", + setup: func(t *testing.T, transport *httpmock.MockTransport) { + transport.RegisterResponder(http.MethodGet, "/conn/error", + httpmock.ConnectionFailure) + }, + url: "/conn/error", + wantErr: cmpopts.AnyError, + }, } { t.Run(tc.name, func(t *testing.T) { transport := newMockTransport(t)