Introducing Contexts

Contexts have been added to all API requests, in addition to other linting fixes
This commit is contained in:
densestvoid
2021-01-22 16:47:22 -05:00
parent 646bec0e27
commit f92a8a7a86
33 changed files with 374 additions and 542 deletions

View File

@ -1,13 +1,15 @@
// Package groupme defines a client capable of executing API commands for the GroupMe chat service
package groupme
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
)
// Endpoints are added on to the GroupMeAPIBase to get the full URI.
// GroupMeAPIBase - Endpoints are added on to this to get the full URI.
// Overridable for testing
const GroupMeAPIBase = "https://api.groupme.com/v3"
@ -40,7 +42,7 @@ func (c Client) String() string {
return marshal(&c)
}
///// Handle parsing of nested interface type response /////
/*/// Handle parsing of nested interface type response ///*/
type jsonResponse struct {
Response response `json:"response"`
Meta `json:"meta"`
@ -58,7 +60,10 @@ func (r response) UnmarshalJSON(bs []byte) error {
return json.NewDecoder(bytes.NewBuffer(bs)).Decode(r.i)
}
func (c Client) do(req *http.Request, i interface{}) error {
const errorStatusCodeMin = 300
func (c Client) do(ctx context.Context, req *http.Request, i interface{}) error {
req = req.WithContext(ctx)
if req.Method == "POST" {
req.Header.Set("Content-Type", "application/json")
}
@ -69,9 +74,10 @@ func (c Client) do(req *http.Request, i interface{}) error {
}
defer getResp.Body.Close()
var readBytes []byte
// Check Status Code is 1XX or 2XX
if getResp.StatusCode/100 > 2 {
bytes, err := ioutil.ReadAll(getResp.Body)
if getResp.StatusCode >= errorStatusCodeMin {
readBytes, err = ioutil.ReadAll(getResp.Body)
if err != nil {
// We couldn't read the output. Oh well; generate the appropriate error type anyway.
return &Meta{
@ -80,7 +86,7 @@ func (c Client) do(req *http.Request, i interface{}) error {
}
resp := newJSONResponse(nil)
if err := json.Unmarshal(bytes, &resp); err != nil {
if err = json.Unmarshal(readBytes, &resp); err != nil {
// We couldn't parse the output. Oh well; generate the appropriate error type anyway.
return &Meta{
Code: HTTPStatusCode(getResp.StatusCode),
@ -93,24 +99,24 @@ func (c Client) do(req *http.Request, i interface{}) error {
return nil
}
bytes, err := ioutil.ReadAll(getResp.Body)
readBytes, err = ioutil.ReadAll(getResp.Body)
if err != nil {
return err
}
resp := newJSONResponse(i)
if err := json.Unmarshal(bytes, &resp); err != nil {
if err := json.Unmarshal(readBytes, &resp); err != nil {
return err
}
return nil
}
func (c Client) doWithAuthToken(req *http.Request, i interface{}) error {
func (c Client) doWithAuthToken(ctx context.Context, req *http.Request, i interface{}) error {
URL := req.URL
query := URL.Query()
query.Set("token", c.authorizationToken)
URL.RawQuery = query.Encode()
return c.do(req, i)
return c.do(ctx, req, i)
}