From 45fd2652642b3cb6fef76ffb2c8c004212c816cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Paulo=20Sima=CC=83o?= Date: Tue, 26 Oct 2021 22:35:31 -0300 Subject: [PATCH] Improved error handling --- lib.go | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/lib.go b/lib.go index 53fc0e2..e5649d8 100644 --- a/lib.go +++ b/lib.go @@ -4,10 +4,10 @@ import ( "bytes" "encoding/json" "errors" + "fmt" "io" "net/http" "strings" - "fmt" ) type Cli struct { @@ -56,11 +56,15 @@ func (c *Cli) Do(method string, strurl string, body []byte) (*http.Response, err req.Header.Set(k, v) } } - res,err:= c.cli.Do(req) - if err==nil && res.StatusCode >=400{ - return nil, errors.New(fmt.Sprintf("Http return code - %d: %s",res.StatusCode,res.Status)) + res, err := c.cli.Do(req) + if err != nil { + return nil, err } - return res,err + defer res.Body.Close() + if res.StatusCode >= 400 { + return nil, errors.New(fmt.Sprintf("Http return code - %d: %s", res.StatusCode, res.Status)) + } + return res, err } func (c *Cli) DoJson(method string, strurl string, i interface{}, o interface{}) (err error) { bs, err := json.Marshal(i)