Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions client/base_client.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package client

import (
"context"
"net/http"
"net/url"
"time"
Expand All @@ -14,3 +15,9 @@ type BaseClient interface {
SetOauth(auth OAuth)
OAuth() OAuth
}

type BaseClientWithContext interface {
BaseClient
SendRequestWithContext(ctx context.Context, method string, rawURL string, data url.Values,
headers map[string]interface{}, body ...byte) (*http.Response, error)
}
12 changes: 9 additions & 3 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ var userAgentOnce sync.Once
func (c *Client) SendRequest(method string, rawURL string, data url.Values,
headers map[string]interface{}, body ...byte) (*http.Response, error) {

return c.SendRequestWithContext(context.Background(), method, rawURL, data, headers, body...)
}

func (c *Client) SendRequestWithContext(ctx context.Context, method string, rawURL string, data url.Values,
headers map[string]interface{}, body ...byte) (*http.Response, error) {

contentType := extractContentTypeHeader(headers)

u, err := url.Parse(rawURL)
Expand Down Expand Up @@ -167,7 +173,7 @@ func (c *Client) SendRequest(method string, rawURL string, data url.Values,
//data is already processed and information will be added to u(the url) in the
//previous step. Now body will solely contain json payload
if contentType == jsonContentType {
req, err = http.NewRequest(method, u.String(), bytes.NewBuffer(body))
req, err = http.NewRequestWithContext(ctx, method, u.String(), bytes.NewBuffer(body))
if err != nil {
return nil, err
}
Expand All @@ -177,7 +183,7 @@ func (c *Client) SendRequest(method string, rawURL string, data url.Values,
if method == http.MethodPost || method == http.MethodPut || method == http.MethodPatch {
valueReader = strings.NewReader(data.Encode())
}
req, err = http.NewRequestWithContext(context.Background(), method, u.String(), valueReader)
req, err = http.NewRequestWithContext(ctx, method, u.String(), valueReader)
if err != nil {
return nil, err
}
Expand All @@ -203,7 +209,7 @@ func (c *Client) SendRequest(method string, rawURL string, data url.Values,
}
if c.OAuth() != nil {
oauth := c.OAuth()
token, _ := c.OAuth().GetAccessToken(context.TODO())
token, _ := c.OAuth().GetAccessToken(ctx)
if token != "" {
req.Header.Add("Authorization", "Bearer "+token)
}
Expand Down
9 changes: 7 additions & 2 deletions client/page_util.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package client

import (
"context"
"encoding/json"
"fmt"
"strings"
Expand All @@ -25,13 +26,17 @@ func ReadLimits(pageSize *int, limit *int) int {
}
}

func GetNext(baseUrl string, response interface{}, getNextPage func(nextPageUri string) (interface{}, error)) (interface{}, error) {
func GetNext(baseUrl string, response interface{}, getNextPage func(ctx context.Context, nextPageUri string) (interface{}, error)) (interface{}, error) {
return GetNextWithContext(context.Background(), baseUrl, response, getNextPage)
}

func GetNextWithContext(ctx context.Context, baseUrl string, response interface{}, getNextPage func(ctx context.Context, nextPageUri string) (interface{}, error)) (interface{}, error) {
nextPageUrl, err := getNextPageUrl(baseUrl, response)
if err != nil {
return nil, err
}

return getNextPage(nextPageUrl)
return getNextPage(ctx, nextPageUrl)
}

func toMap(s interface{}) (map[string]interface{}, error) {
Expand Down
7 changes: 4 additions & 3 deletions client/page_util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package client

import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
Expand Down Expand Up @@ -140,7 +141,7 @@ type testMessage struct {
To *string `json:"to,omitempty"`
}

func getSomething(nextPageUrl string) (interface{}, error) {
func getSomething(ctx context.Context, nextPageUrl string) (interface{}, error) {
return nextPageUrl, nil
}

Expand All @@ -151,11 +152,11 @@ func TestPageUtil_GetNext(t *testing.T) {
ps := &testResponse{}
_ = json.NewDecoder(response.Body).Decode(ps)

nextPageUrl, err := GetNext(baseUrl, ps, getSomething)
nextPageUrl, err := GetNextWithContext(context.Background(), baseUrl, ps, getSomething)
assert.Equal(t, "https://api.twilio.com/2010-04-01/Accounts/ACXX/Messages.json?From=9999999999&PageNumber=&To=4444444444&PageSize=2&Page=1&PageToken=PASMXX", nextPageUrl)
assert.Nil(t, err)

nextPageUrl, err = GetNext(baseUrl, nil, getSomething)
nextPageUrl, err = GetNextWithContext(context.Background(), baseUrl, nil, getSomething)
assert.Empty(t, nextPageUrl)
assert.Nil(t, err)
}
Expand Down
54 changes: 42 additions & 12 deletions client/request_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,42 @@
package client

import (
"context"
"net/http"
"net/url"
"os"
"strings"
)

type RequestHandler struct {
Client BaseClient
Edge string
Region string
Client BaseClient
Edge string
Region string
clientWithContext BaseClientWithContext
}

func NewRequestHandler(client BaseClient) *RequestHandler {
// If the base client supports context, add it to the request handler.
// Otherwise we leave it nil and the base client will be used.
clientWithContext, _ := client.(BaseClientWithContext)
Comment on lines +20 to +22
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Admittedly this is less than ideal, but it allows us to add Context support without breaking backwards compatibility.


return &RequestHandler{
Client: client,
Edge: os.Getenv("TWILIO_EDGE"),
Region: os.Getenv("TWILIO_REGION"),
Client: client,
Edge: os.Getenv("TWILIO_EDGE"),
Region: os.Getenv("TWILIO_REGION"),
clientWithContext: clientWithContext,
}
}

func (c *RequestHandler) sendRequest(method string, rawURL string, data url.Values,
func (c *RequestHandler) sendRequest(ctx context.Context, method string, rawURL string, data url.Values,
headers map[string]interface{}, body ...byte) (*http.Response, error) {
parsedURL, err := c.BuildUrl(rawURL)
if err != nil {
return nil, err
}
if c.clientWithContext != nil {
return c.clientWithContext.SendRequestWithContext(ctx, method, parsedURL, data, headers, body...)
}
return c.Client.SendRequest(method, parsedURL, data, headers, body...)
}

Expand Down Expand Up @@ -83,21 +93,41 @@ func (c *RequestHandler) BuildUrl(rawURL string) (string, error) {
}

func (c *RequestHandler) Post(path string, bodyData url.Values, headers map[string]interface{}, body ...byte) (*http.Response, error) {
return c.sendRequest(http.MethodPost, path, bodyData, headers, body...)
return c.PostWithContext(context.Background(), path, bodyData, headers, body...)
}

func (c *RequestHandler) PostWithContext(ctx context.Context, path string, bodyData url.Values, headers map[string]interface{}, body ...byte) (*http.Response, error) {
return c.clientWithContext.SendRequestWithContext(ctx, http.MethodPost, path, bodyData, headers, body...)
}

func (c *RequestHandler) Put(path string, bodyData url.Values, headers map[string]interface{}, body ...byte) (*http.Response, error) {
return c.sendRequest(http.MethodPut, path, bodyData, headers, body...)
return c.PutWithContext(context.Background(), path, bodyData, headers, body...)
}

func (c *RequestHandler) PutWithContext(ctx context.Context, path string, bodyData url.Values, headers map[string]interface{}, body ...byte) (*http.Response, error) {
return c.clientWithContext.SendRequestWithContext(ctx, http.MethodPut, path, bodyData, headers, body...)
}

func (c *RequestHandler) Patch(path string, bodyData url.Values, headers map[string]interface{}, body ...byte) (*http.Response, error) {
return c.sendRequest(http.MethodPatch, path, bodyData, headers, body...)
return c.PatchWithContext(context.Background(), path, bodyData, headers, body...)
}

func (c *RequestHandler) PatchWithContext(ctx context.Context, path string, bodyData url.Values, headers map[string]interface{}, body ...byte) (*http.Response, error) {
return c.clientWithContext.SendRequestWithContext(ctx, http.MethodPatch, path, bodyData, headers, body...)
}

func (c *RequestHandler) Get(path string, queryData url.Values, headers map[string]interface{}) (*http.Response, error) {
return c.sendRequest(http.MethodGet, path, queryData, headers)
return c.GetWithContext(context.Background(), path, queryData, headers)
}

func (c *RequestHandler) GetWithContext(ctx context.Context, path string, queryData url.Values, headers map[string]interface{}) (*http.Response, error) {
return c.clientWithContext.SendRequestWithContext(ctx, http.MethodGet, path, queryData, headers)
}

func (c *RequestHandler) Delete(path string, queryData url.Values, headers map[string]interface{}) (*http.Response, error) {
return c.sendRequest(http.MethodDelete, path, queryData, headers)
return c.DeleteWithContext(context.Background(), path, queryData, headers)
}

func (c *RequestHandler) DeleteWithContext(ctx context.Context, path string, queryData url.Values, headers map[string]interface{}) (*http.Response, error) {
return c.clientWithContext.SendRequestWithContext(ctx, http.MethodDelete, path, queryData, headers)
}
5 changes: 3 additions & 2 deletions client/request_handler_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package client_test

import (
"context"
"errors"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -83,7 +84,7 @@ func TestRequestHandler_SendGetRequest(t *testing.T) {
defer errorServer.Close()

requestHandler := NewRequestHandler("user", "pass")
resp, err := requestHandler.Get(errorServer.URL, nil, nil) //nolint:bodyclose
resp, err := requestHandler.GetWithContext(context.Background(), errorServer.URL, nil, nil) //nolint:bodyclose
twilioError := err.(*client.TwilioRestError)
assert.Nil(t, resp)
assert.Equal(t, 400, twilioError.Status)
Expand All @@ -108,7 +109,7 @@ func TestRequestHandler_SendPostRequest(t *testing.T) {
defer errorServer.Close()

requestHandler := NewRequestHandler("user", "pass")
resp, err := requestHandler.Post(errorServer.URL, nil, nil) //nolint:bodyclose
resp, err := requestHandler.PostWithContext(context.Background(), errorServer.URL, nil, nil) //nolint:bodyclose
twilioError := err.(*client.TwilioRestError)
assert.Nil(t, resp)
assert.Equal(t, 400, twilioError.Status)
Expand Down
25 changes: 25 additions & 0 deletions cluster_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package twilio

import (
"context"
"os"
"testing"

Expand All @@ -15,6 +16,7 @@ import (
EventsV1 "github.com/twilio/twilio-go/rest/events/v1"

"github.com/stretchr/testify/assert"

IamV1 "github.com/twilio/twilio-go/rest/iam/v1"
)

Expand Down Expand Up @@ -268,3 +270,26 @@ func TestOrgsScimUerList(t *testing.T) {
assert.Nil(t, err)
assert.NotNil(t, users)
}

func TestSendingATextWithContext(t *testing.T) {
params := &Api.CreateMessageParams{}
params.SetTo(to)
params.SetFrom(from)
params.SetBody("Hello there")

resp, err := testClient.Api.CreateMessageWithContext(context.Background(), params)
assert.Nil(t, err)
assert.NotNil(t, resp)
assert.Equal(t, "Hello there", *resp.Body)
assert.Equal(t, from, *resp.From)
assert.Equal(t, to, *resp.To)
}

func TestOrgsAccountsListWithContext(t *testing.T) {
listAccounts, err := orgsClient.PreviewIamOrganization.ListOrganizationAccountsWithContext(context.Background(), orgSid, &PreviewIam.ListOrganizationAccountsParams{})
assert.Nil(t, err)
assert.NotNil(t, listAccounts)
accounts, err := orgsClient.PreviewIamOrganization.FetchOrganizationAccountWithContext(context.Background(), orgSid, &PreviewIam.FetchOrganizationAccountParams{PathAccountSid: &accountSidOrgs})
assert.Nil(t, err)
assert.NotNil(t, accounts)
}
2 changes: 1 addition & 1 deletion oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func (a *APIOAuth) GetAccessToken(ctx context.Context) (string, error) {
SetClientId(a.creds.ClientId).
SetClientSecret(a.creds.ClientSecret)
a.iamService.RequestHandler().Client.SetOauth(nil) // set oauth to nil to make no-auth request
token, err := a.iamService.CreateToken(params)
token, err := a.iamService.CreateTokenWithContext(ctx, params)
if err == nil {
a.tokenAuth = TokenAuth{
Token: *token.AccessToken,
Expand Down