From 7f8d829ff7489dbcfb5ade5ffeec0fded4f8a237 Mon Sep 17 00:00:00 2001 From: Douglas Danger Manley Date: Sun, 20 Dec 2020 13:28:12 -0500 Subject: [PATCH 1/2] Return the Meta on error Previously, this would never actually return the Meta data structure since by the time that it got parsed, we already knew that the request was good. Now, we do a special parse when we know that it failed so that we can return the structured data (in particular, we want to be able to use the HTTP status code). --- client.go | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/client.go b/client.go index 4cac25d..7b1a712 100644 --- a/client.go +++ b/client.go @@ -3,7 +3,6 @@ package groupme import ( "bytes" "encoding/json" - "fmt" "io/ioutil" "net/http" ) @@ -77,7 +76,14 @@ func (c Client) do(req *http.Request, i interface{}) error { // Check Status Code is 1XX or 2XX if getResp.StatusCode/100 > 2 { - return fmt.Errorf("%s: %s", getResp.Status, string(bytes)) + resp := newJSONResponse(nil) + if err := json.Unmarshal(bytes, &resp); err != nil { + // We couldn't parse the output. Oh well; generate the appropriate error type anyway. + return &Meta{ + Code: HTTPStatusCode(getResp.StatusCode), + } + } + return &resp.Meta } if i == nil { @@ -89,11 +95,6 @@ func (c Client) do(req *http.Request, i interface{}) error { return err } - // Check Status Code is 1XX or 2XX - if resp.Meta.Code/100 > 2 { - return &resp.Meta - } - return nil } From 73586d4b4c550fc987e4259db352500ba3ed03ba Mon Sep 17 00:00:00 2001 From: Douglas Danger Manley Date: Sun, 20 Dec 2020 13:35:13 -0500 Subject: [PATCH 2/2] Ensure that we return the correct error code even if we can't read the body --- client.go | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/client.go b/client.go index 7b1a712..a3c1b57 100644 --- a/client.go +++ b/client.go @@ -69,13 +69,16 @@ func (c Client) do(req *http.Request, i interface{}) error { } defer getResp.Body.Close() - bytes, err := ioutil.ReadAll(getResp.Body) - if err != nil { - return err - } - // Check Status Code is 1XX or 2XX if getResp.StatusCode/100 > 2 { + bytes, err := ioutil.ReadAll(getResp.Body) + if err != nil { + // We couldn't read the output. Oh well; generate the appropriate error type anyway. + return &Meta{ + Code: HTTPStatusCode(getResp.StatusCode), + } + } + resp := newJSONResponse(nil) if err := json.Unmarshal(bytes, &resp); err != nil { // We couldn't parse the output. Oh well; generate the appropriate error type anyway. @@ -90,6 +93,11 @@ func (c Client) do(req *http.Request, i interface{}) error { return nil } + bytes, err := ioutil.ReadAll(getResp.Body) + if err != nil { + return err + } + resp := newJSONResponse(i) if err := json.Unmarshal(bytes, &resp); err != nil { return err