From a97c3d833763cdee27115fd1ab22c33e5a850145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Thu, 13 Oct 2022 17:38:31 +0200 Subject: [PATCH] Fix HTTP error handling in `RESTClient.Request()` method - Ensure that `Request()` calls HandleHTTPError so that any JSON error body properly gets parsed; - Ensure that response body is closed after reading the error response. --- example_gh_test.go | 4 ---- internal/api/rest_client.go | 9 +++------ 2 files changed, 3 insertions(+), 10 deletions(-) diff --git a/example_gh_test.go b/example_gh_test.go index 5cfc161..f41b88a 100644 --- a/example_gh_test.go +++ b/example_gh_test.go @@ -77,10 +77,6 @@ func ExampleRESTClient_request() { } defer resp.Body.Close() - if resp.StatusCode > 299 { - log.Fatal("server error") - } - f, err := os.CreateTemp("", "*_checksums.txt") if err != nil { log.Fatal(err) diff --git a/internal/api/rest_client.go b/internal/api/rest_client.go index c95770b..a086ded 100644 --- a/internal/api/rest_client.go +++ b/internal/api/rest_client.go @@ -33,16 +33,13 @@ func (c restClient) RequestWithContext(ctx context.Context, method string, path resp, err := c.client.Do(req) if err != nil { - return resp, err + return nil, err } success := resp.StatusCode >= 200 && resp.StatusCode < 300 if !success { - err = api.HTTPError{ - Headers: resp.Header, - RequestURL: resp.Request.URL, - StatusCode: resp.StatusCode, - } + defer resp.Body.Close() + return nil, api.HandleHTTPError(resp) } return resp, err