api: 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.
This commit is contained in:
James Rasell
2019-11-08 16:04:15 +01:00
committed by James Rasell
parent 9ced0468f6
commit d890ddbfd9
2 changed files with 13 additions and 6 deletions

View File

@@ -5,6 +5,7 @@ import (
"compress/gzip"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net"
@@ -930,8 +931,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

View File

@@ -413,17 +413,15 @@ func (n *Nodes) Stats(nodeID string, q *QueryOptions) (*HostStats, error) {
}
func (n *Nodes) GC(nodeID string, q *QueryOptions) error {
var resp struct{}
path := fmt.Sprintf("/v1/client/gc?node_id=%s", nodeID)
_, err := n.client.query(path, &resp, q)
_, err := n.client.query(path, nil, q)
return err
}
// 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
}