Created
April 27, 2020 10:44
-
-
Save plutov/04c317b4f20addaeba009e98d2e12a18 to your computer and use it in GitHub Desktop.
api-client-6.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func (c *Client) sendRequest(req *http.Request, v interface{}) error { | |
req.Header.Set("Content-Type", "application/json; charset=utf-8") | |
req.Header.Set("Accept", "application/json; charset=utf-8") | |
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.apiKey)) | |
res, err := c.HTTPClient.Do(req) | |
if err != nil { | |
return err | |
} | |
defer res.Body.Close() | |
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest { | |
var errRes errorResponse | |
if err = json.NewDecoder(res.Body).Decode(&errRes); err == nil { | |
return errors.New(errRes.Message) | |
} | |
return fmt.Errorf("unknown error, status code: %d", res.StatusCode) | |
} | |
fullResponse := successResponse{ | |
Data: v, | |
} | |
if err = json.NewDecoder(res.Body).Decode(&fullResponse); err != nil { | |
return err | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment