From 5673b1076c50bb2b123982610ab6e27cbd59cb2f Mon Sep 17 00:00:00 2001 From: James Rasell Date: Mon, 29 Jul 2019 10:37:33 +0200 Subject: [PATCH] Update API to check response content length before decoding. The API decodeBody function will now check the content length before attempting to decode. If the length is zero, and the out interface is nil then it is safe to assume the API call is not returning any data to the user. This allows us to better handle passing nil to API calls in a single place. --- api/api.go | 19 +++++++++++++------ api/nodes.go | 3 +-- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/api/api.go b/api/api.go index 9b41bf94719e..85a06f3edd04 100644 --- a/api/api.go +++ b/api/api.go @@ -5,6 +5,7 @@ import ( "compress/gzip" "crypto/tls" "encoding/json" + "errors" "fmt" "io" "net" @@ -769,10 +770,8 @@ func (c *Client) query(endpoint string, out interface{}, q *QueryOptions) (*Quer parseQueryMeta(resp, qm) qm.RequestTime = rtt - if out != nil { - if err := decodeBody(resp, out); err != nil { - return nil, err - } + if err := decodeBody(resp, out); err != nil { + return nil, err } return qm, nil } @@ -897,8 +896,16 @@ func parseWriteMeta(resp *http.Response, q *WriteMeta) error { // decodeBody is used to JSON decode a body func decodeBody(resp *http.Response, out interface{}) error { - dec := json.NewDecoder(resp.Body) - return dec.Decode(out) + switch resp.ContentLength { + case 0: + if out == nil { + return nil + } + return errors.New("Got 0 byte response with non-nil decode object") + default: + dec := json.NewDecoder(resp.Body) + return dec.Decode(out) + } } // encodeBody is used to encode a request body diff --git a/api/nodes.go b/api/nodes.go index a7e542dfeee6..437ec2bc9249 100644 --- a/api/nodes.go +++ b/api/nodes.go @@ -420,9 +420,8 @@ func (n *Nodes) GC(nodeID string, q *QueryOptions) error { // TODO Add tests func (n *Nodes) GcAlloc(allocID string, q *QueryOptions) error { - var resp struct{} path := fmt.Sprintf("/v1/client/allocation/%s/gc", allocID) - _, err := n.client.query(path, &resp, q) + _, err := n.client.query(path, nil, q) return err }