From b17008d1f1e601e10a94977608fb0b3fa4fbe944 Mon Sep 17 00:00:00 2001 From: fnaoto Date: Sat, 10 Dec 2022 14:14:51 +0900 Subject: [PATCH 1/2] Fix json decode. --- client.go | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/client.go b/client.go index bcf776d..113e0ef 100644 --- a/client.go +++ b/client.go @@ -1,7 +1,6 @@ package deploygate import ( - "bytes" "encoding/json" "errors" "fmt" @@ -114,21 +113,18 @@ func (c *Client) NewRequest(httpRequest *HttpRequest) (*http.Response, error) { func (c *Client) Decode(resp *http.Response, out interface{}) error { defer resp.Body.Close() - buf := new(bytes.Buffer) - buf.ReadFrom(resp.Body) - if resp.StatusCode >= 300 { - return fmt.Errorf("status code is %v, body is %v", resp.StatusCode, buf.String()) + return fmt.Errorf("status code is %v, body is %v", resp.StatusCode, resp.Body) } if resp.ContentLength == 0 { return nil } - err := json.Unmarshal(buf.Bytes(), &out) + err := json.NewDecoder(resp.Body).Decode(&out) if err != nil { - return fmt.Errorf("%v, output type is %T, body is %v", err, out, buf.String()) + return fmt.Errorf("%v, output type is %T, body is %v", err, out, resp.Body) } return nil From 07f9915d48fa7a67d4c05632b7e069eaed315e58 Mon Sep 17 00:00:00 2001 From: fnaoto Date: Sat, 10 Dec 2022 17:47:05 +0900 Subject: [PATCH 2/2] Add buf check. --- client.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/client.go b/client.go index 113e0ef..bcfdc94 100644 --- a/client.go +++ b/client.go @@ -1,6 +1,7 @@ package deploygate import ( + "bytes" "encoding/json" "errors" "fmt" @@ -113,18 +114,25 @@ func (c *Client) NewRequest(httpRequest *HttpRequest) (*http.Response, error) { func (c *Client) Decode(resp *http.Response, out interface{}) error { defer resp.Body.Close() + buf := new(bytes.Buffer) + buf.ReadFrom(resp.Body) + if resp.StatusCode >= 300 { - return fmt.Errorf("status code is %v, body is %v", resp.StatusCode, resp.Body) + return fmt.Errorf("status code is %v, body is %v", resp.StatusCode, buf.String()) } if resp.ContentLength == 0 { return nil } - err := json.NewDecoder(resp.Body).Decode(&out) + if buf.String() == "" { + return nil + } + + err := json.Unmarshal(buf.Bytes(), &out) if err != nil { - return fmt.Errorf("%v, output type is %T, body is %v", err, out, resp.Body) + return fmt.Errorf("%v, output type is %T, body is %v", err, out, buf.String()) } return nil