From 20c866ea8a9d59852e60e56961578778ebafdc47 Mon Sep 17 00:00:00 2001 From: Ivan Markin Date: Tue, 26 Feb 2019 22:11:34 +0000 Subject: [PATCH] Print response body on failure; properly close response body --- forecast/forecast.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/forecast/forecast.go b/forecast/forecast.go index baa0f2d..949eec7 100644 --- a/forecast/forecast.go +++ b/forecast/forecast.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "fmt" + "io/ioutil" "net/http" ) @@ -224,10 +225,15 @@ func Get(uri string, data Request) (forecast Forecast, err error) { return forecast, fmt.Errorf("Http request to %s failed: %s", req.URL, err.Error()) } + defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return forecast, fmt.Errorf("Http request to %s failed with status code: %v", req.URL, resp.StatusCode) + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return forecast, fmt.Errorf("Reading error response failed: %v", err) + } + body = bytes.TrimRight(body, "\n") + return forecast, fmt.Errorf("Http request to %s failed with status code %v: %s", req.URL, resp.StatusCode, body) } - defer resp.Body.Close() // decode the body dec := json.NewDecoder(resp.Body)