From 0cab49f08261305f334e8b39038211f1578a80a3 Mon Sep 17 00:00:00 2001 From: pancho horrillo Date: Tue, 8 Oct 2019 05:42:33 +0200 Subject: [PATCH] Simplify handling of http.Client response MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As per the doc¹: If the returned error is nil, the Response will contain a non-nil Body which the user is expected to close. ... On error, any Response can be ignored. A non-nil Response with a non-nil error only occurs when CheckRedirect fails, and even then the returned Response.Body is already closed. It is thus safe to defer res.Body.Close() as soon as err has been determined to be nil. Also, I've dispensed with the separate variable client, since it is not used later. ¹: https://godoc.org/net/http#Client.Do --- internal/http/request.go | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/internal/http/request.go b/internal/http/request.go index 4ea7c83..7c6fa00 100644 --- a/internal/http/request.go +++ b/internal/http/request.go @@ -43,16 +43,11 @@ func Request(method string, url string, contentType string, r io.Reader, w io.Wr req.Header.Add("Content-Type", contentType) } - client := &http.Client{} - res, err := client.Do(req) - - if res != nil { - defer res.Body.Close() - } - + res, err := new(http.Client).Do(req) if err != nil { return err } + defer res.Body.Close() if res.StatusCode < 200 || res.StatusCode >= 300 { return errors.New(GetReason(res))