Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Print response body on failure; properly close response body #66

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions forecast/forecast.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)

Expand Down Expand Up @@ -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)
Expand Down