Skip to content

Commit

Permalink
Do not attempt to standardise response bodies when we don't need to (t…
Browse files Browse the repository at this point in the history
…ailscale#20)

Related to https://github.com/davidsbond/terraform-provider-tailscale/issues/113

This commit modifies the request making code to not attempt to standardise
response bodies if we are not attempting to parse the response. For example, the
tailnet key delete API response has an empty body, which would cause errors when
calling hujson.Standardize.

Signed-off-by: David Bond <davidsbond93@gmail.com>
  • Loading branch information
davidsbond committed Jun 11, 2022
1 parent fc53730 commit 04fd877
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
25 changes: 17 additions & 8 deletions tailscale/client.go
Expand Up @@ -123,11 +123,24 @@ func (c *Client) performRequest(req *http.Request, out interface{}) error {
if err != nil {
return err
}
if !json.Valid(body) {
body, err = hujson.Standardize(body)
if err != nil {
return err

if res.StatusCode >= http.StatusOK && res.StatusCode < http.StatusMultipleChoices {
// If we don't care about the response body, leave. This check is required as some
// API responses have empty bodies, so we don't want to try and standardize them for
// parsing.
if out == nil {
return nil
}

// If we've got hujson back, convert it to JSON, so we can natively parse it.
if !json.Valid(body) {
body, err = hujson.Standardize(body)
if err != nil {
return err
}
}

return json.Unmarshal(body, out)
}

if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusCreated {
Expand All @@ -140,10 +153,6 @@ func (c *Client) performRequest(req *http.Request, out interface{}) error {
return apiErr
}

if out != nil {
return json.Unmarshal(body, out)
}

return nil
}

Expand Down
4 changes: 3 additions & 1 deletion tailscale/tailscale_test.go
Expand Up @@ -67,5 +67,7 @@ func (t *TestServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
assert.NoError(t.t, err)

w.WriteHeader(t.ResponseCode)
assert.NoError(t.t, json.NewEncoder(w).Encode(t.ResponseBody))
if t.ResponseBody != nil {
assert.NoError(t.t, json.NewEncoder(w).Encode(t.ResponseBody))
}
}

0 comments on commit 04fd877

Please sign in to comment.