Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Support JSON payload in HTTP requests #213

Merged
merged 10 commits into from
Oct 27, 2023
63 changes: 52 additions & 11 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
"encoding/json"
"fmt"
"net/http"
"bytes"
"net/url"
"regexp"
"runtime"
"strconv"
"strings"
"time"

"github.com/pkg/errors"
"github.com/twilio/twilio-go/client/form"
)
Expand Down Expand Up @@ -56,7 +56,27 @@
c.HTTPClient.Timeout = timeout
}

func extractContentTypeHeader(headers map[string]interface{}) (cType string){
headerType, ok := headers["Content-Type"]
if !ok {
return urlEncodedContentType
}
return headerType.(string)
AsabuHere marked this conversation as resolved.
Show resolved Hide resolved
}

func decodeJsonPayload(jsonBody string)(s []byte){
prefixTrimmedString := jsonBody[2:]
AsabuHere marked this conversation as resolved.
Show resolved Hide resolved
suffixTrimmedString := prefixTrimmedString[:len(prefixTrimmedString)-2]
finalJsonPayload := jsonPrefix + suffixTrimmedString + jsonSuffix
finalJsonPayloadArray := []byte(finalJsonPayload)
return finalJsonPayloadArray
}

const (
urlEncodedContentType = "application/x-www-form-urlencoded"
jsonContentType = "application/json"
jsonPrefix = "{"
jsonSuffix = "}"
keepZeros = true
delimiter = '.'
escapee = '\\'
Expand Down Expand Up @@ -90,13 +110,17 @@
// SendRequest verifies, constructs, and authorizes an HTTP request.
func (c *Client) SendRequest(method string, rawURL string, data url.Values,
headers map[string]interface{}) (*http.Response, error) {

AsabuHere marked this conversation as resolved.
Show resolved Hide resolved
contentType := extractContentTypeHeader(headers)

u, err := url.Parse(rawURL)
if err != nil {
return nil, err
}

valueReader := &strings.Reader{}
goVersion := runtime.Version()
var req *http.Request

if method == http.MethodGet {
if data != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

Previously only GET method was supposed to have query parameter, going forward any method can have query parameter.

Expand All @@ -108,13 +132,35 @@
}
}

if method == http.MethodPost {
valueReader = strings.NewReader(data.Encode())
if contentType == jsonContentType {
var jsonData []byte
var err error
var encodedString string
for _, value := range data {
jsonData, err = json.Marshal(value[0])

Check failure on line 140 in client/client.go

View workflow job for this annotation

GitHub Actions / Build & Test (1.16)

ineffectual assignment to err (ineffassign)
AsabuHere marked this conversation as resolved.
Show resolved Hide resolved
encodedString, err = url.QueryUnescape(string(jsonData))
AsabuHere marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil, err
}
}
jsonBody := decodeJsonPayload(encodedString)
req, err = http.NewRequest(method, u.String(), bytes.NewBuffer(jsonBody))
if err != nil {
return nil, err
}
} else {
if method == http.MethodPost {
Copy link
Contributor

Choose a reason for hiding this comment

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

Going forward PUT method can be used for update operation which will have request body.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Should i add support for that as well now?

valueReader = strings.NewReader(data.Encode())
}
req, err = http.NewRequest(method, u.String(), valueReader)
if err != nil {
return nil, err
}

}

req, err := http.NewRequest(method, u.String(), valueReader)
if err != nil {
return nil, err
if contentType == urlEncodedContentType{
req.Header.Add("Content-Type", urlEncodedContentType)
}

req.SetBasicAuth(c.basicAuth())
Expand All @@ -128,14 +174,9 @@

req.Header.Add("User-Agent", userAgent)

if method == http.MethodPost {
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
}

for k, v := range headers {
req.Header.Add(k, fmt.Sprint(v))
}

return c.doWithErr(req)
}

Expand Down
67 changes: 67 additions & 0 deletions rest/previewmessaging/v1/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Go API client for openapi

Bulk Sending is a public Twilio REST API for 1:Many Message creation up to 100 recipients. Broadcast is a public Twilio REST API for 1:Many Message creation up to 10,000 recipients via file upload.

## Overview
This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project from the OpenAPI specs located at [twilio/twilio-oai](https://github.com/twilio/twilio-oai/tree/main/spec). By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client.

- API version: 1.0.0-alpha.1
- Package version: 1.0.0
- Build package: com.twilio.oai.TwilioGoGenerator
For more information, please visit [https://support.twilio.com](https://support.twilio.com)

## Installation

Install the following dependencies:

```shell
go get github.com/stretchr/testify/assert
go get golang.org/x/net/context
```

Put the package under your project folder and add the following in import:

```golang
import "./openapi"
```

## Documentation for API Endpoints

All URIs are relative to *https://preview.messaging.twilio.com*

Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*BroadcastsApi* | [**CreateBroadcast**](docs/BroadcastsApi.md#createbroadcast) | **Post** /v1/Broadcasts |
*MessagesApi* | [**CreateMessages**](docs/MessagesApi.md#createmessages) | **Post** /v1/Messages |


## Documentation For Models

- [MessagingV1MessageReceipt](docs/MessagingV1MessageReceipt.md)
- [MessagingV1BroadcastExecutionDetails](docs/MessagingV1BroadcastExecutionDetails.md)
- [MessagingV1Message](docs/MessagingV1Message.md)
- [MessagingV1FailedMessageReceipt](docs/MessagingV1FailedMessageReceipt.md)
- [MessagingV1CreateMessagesResult](docs/MessagingV1CreateMessagesResult.md)
- [CreateMessagesRequest](docs/CreateMessagesRequest.md)
- [MessagingV1Error](docs/MessagingV1Error.md)
- [MessagingV1Broadcast](docs/MessagingV1Broadcast.md)


## Documentation For Authorization



## accountSid_authToken

- **Type**: HTTP basic authentication

Example

```golang
auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{
UserName: "username",
Password: "password",
})
r, err := client.Service.Operation(auth, args)
```

35 changes: 35 additions & 0 deletions rest/previewmessaging/v1/api_service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Bulk Messaging and Broadcast
* Bulk Sending is a public Twilio REST API for 1:Many Message creation up to 100 recipients. Broadcast is a public Twilio REST API for 1:Many Message creation up to 10,000 recipients via file upload.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/

package openapi

import (
twilio "github.com/twilio/twilio-go/client"
)

type ApiService struct {
baseURL string
requestHandler *twilio.RequestHandler
}

func NewApiService(requestHandler *twilio.RequestHandler) *ApiService {
return &ApiService {
requestHandler: requestHandler,
baseURL: "",
}
}

func NewApiServiceWithClient(client twilio.BaseClient) *ApiService {
return NewApiService(twilio.NewRequestHandler(client))
}
57 changes: 57 additions & 0 deletions rest/previewmessaging/v1/broadcasts.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Bulk Messaging and Broadcast
* Bulk Sending is a public Twilio REST API for 1:Many Message creation up to 100 recipients. Broadcast is a public Twilio REST API for 1:Many Message creation up to 10,000 recipients via file upload.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/

package openapi

import (
"encoding/json"
"net/url"
)

// Optional parameters for the method 'CreateBroadcast'
type CreateBroadcastParams struct {
// Idempotency key provided by the client
XTwilioRequestKey *string `json:"X-Twilio-Request-Key,omitempty"`
}

func (params *CreateBroadcastParams) SetXTwilioRequestKey(XTwilioRequestKey string) *CreateBroadcastParams {
params.XTwilioRequestKey = &XTwilioRequestKey
return params
}

// Create a new Broadcast
func (c *ApiService) CreateBroadcast(params *CreateBroadcastParams) (*MessagingV1Broadcast, error) {
path := "/v1/Broadcasts"

data := url.Values{}
headers := make(map[string]interface{})

if params != nil && params.XTwilioRequestKey != nil {
headers["X-Twilio-Request-Key"] = *params.XTwilioRequestKey
}

resp, err := c.requestHandler.Post(c.baseURL+path, data, headers)
if err != nil {
return nil, err
}

defer resp.Body.Close()

ps := &MessagingV1Broadcast{}
if err := json.NewDecoder(resp.Body).Decode(ps); err != nil {
return nil, err
}

return ps, err
}
27 changes: 27 additions & 0 deletions rest/previewmessaging/v1/docs/CreateMessagesRequest.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# CreateMessagesRequest

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Messages** | [**[]MessagingV1Message**](MessagingV1Message.md) | |[optional]
**From** | **string** | A Twilio phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, an [alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id), or a [Channel Endpoint address](https://www.twilio.com/docs/sms/channels#channel-addresses) that is enabled for the type of message you want to send. Phone numbers or [short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from Twilio also work here. You cannot, for example, spoof messages from a private cell phone number. If you are using `messaging_service_sid`, this parameter must be empty. |[optional]
**MessagingServiceSid** | **string** | The SID of the [Messaging Service](https://www.twilio.com/docs/sms/services#send-a-message-with-copilot) you want to associate with the Message. Set this parameter to use the [Messaging Service Settings and Copilot Features](https://www.twilio.com/console/sms/services) you have configured and leave the `from` parameter empty. When only this parameter is set, Twilio will use your enabled Copilot Features to select the `from` phone number for delivery. |[optional]
**Body** | **string** | The text of the message you want to send. Can be up to 1,600 characters in length. |[optional]
**ContentSid** | **string** | The SID of the preconfigured [Content Template](https://www.twilio.com/docs/content-api/create-and-send-your-first-content-api-template#create-a-template) you want to associate with the Message. Must be used in conjuction with a preconfigured [Messaging Service Settings and Copilot Features](https://www.twilio.com/console/sms/services) When this parameter is set, Twilio will use your configured content template and the provided `ContentVariables`. This Twilio product is currently in Private Beta. |[optional]
**MediaUrl** | **[]string** | The URL of the media to send with the message. The media can be of type `gif`, `png`, and `jpeg` and will be formatted correctly on the recipient's device. The media size limit is 5MB for supported file types (JPEG, PNG, GIF) and 500KB for [other types](https://www.twilio.com/docs/sms/accepted-mime-types) of accepted media. To send more than one image in the message body, provide multiple `media_url` parameters in the POST request. You can include up to 10 `media_url` parameters per message. You can send images in an SMS message in only the US and Canada. |[optional]
**StatusCallback** | **string** | The URL we should call using the \"status_callback_method\" to send status information to your application. If specified, we POST these message status changes to the URL - queued, failed, sent, delivered, or undelivered. Twilio will POST its [standard request parameters](https://www.twilio.com/docs/messaging/twiml#request-parameters) as well as some additional parameters including \"MessageSid\", \"MessageStatus\", and \"ErrorCode\". If you include this parameter with the \"messaging_service_sid\", we use this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/messaging/services/api). URLs must contain a valid hostname and underscores are not allowed. |[optional]
**ValidityPeriod** | **int** | How long in seconds the message can remain in our outgoing message queue. After this period elapses, the message fails and we call your status callback. Can be between 1 and the default value of 14,400 seconds. After a message has been accepted by a carrier, however, we cannot guarantee that the message will not be queued after this period. We recommend that this value be at least 5 seconds. |[optional]
**SendAt** | **string** | The time at which Twilio will send the message. This parameter can be used to schedule a message to be sent at a particular time. Must be in ISO 8601 format. |[optional]
**ScheduleType** | **string** | This parameter indicates your intent to schedule a message. Pass the value `fixed` to schedule a message at a fixed time. This parameter works in conjuction with the `SendAt` parameter. |[optional]
**ShortenUrls** | **bool** | Determines the usage of Click Tracking. Setting it to `true` will instruct Twilio to replace all links in the Message with a shortened version based on the associated Domain Sid and track clicks on them. If this parameter is not set on an API call, we will use the value set on the Messaging Service. If this parameter is not set and the value is not configured on the Messaging Service used this will default to `false`. |[optional]
**SendAsMms** | **bool** | If set to True, Twilio will deliver the message as a single MMS message, regardless of the presence of media. |[optional]
**MaxPrice** | **float32** | The maximum total price in US dollars that you will pay for the message to be delivered. Can be a decimal value that has up to 4 decimal places. All messages are queued for delivery and the message cost is checked before the message is sent. If the cost exceeds max_price, the message will fail and a status of Failed is sent to the status callback. If MaxPrice is not set, the message cost is not checked. |[optional]
**Attempt** | **int** | Total number of attempts made ( including this ) to send out the message regardless of the provider used |[optional]
**SmartEncoded** | **bool** | This parameter indicates whether to detect Unicode characters that have a similar GSM-7 character and replace them. Can be true or false. |[optional]
**ForceDelivery** | **bool** | This parameter allows Twilio to send SMS traffic to carriers without checking/caring whether the destination number is a mobile or a landline. |[optional]
**ApplicationSid** | **string** | The SID of the application that should receive message status. We POST a message_sid parameter and a message_status parameter with a value of sent or failed to the application's message_status_callback. If a status_callback parameter is also passed, it will be ignored and the application's message_status_callback parameter will be used. |[optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


16 changes: 16 additions & 0 deletions rest/previewmessaging/v1/docs/MessagingV1Broadcast.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# MessagingV1Broadcast

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**BroadcastSid** | **string** | Numeric ID indentifying individual Broadcast requests |[optional]
**CreatedDate** | [**time.Time**](time.Time.md) | Timestamp of when the Broadcast was created |[optional]
**UpdatedDate** | [**time.Time**](time.Time.md) | Timestamp of when the Broadcast was last updated |[optional]
**BroadcastStatus** | **string** | Status of the Broadcast request. Valid values are None, Pending-Upload, Uploaded, Queued, Executing, Execution-Failure, Execution-Completed, Cancelation-Requested, and Canceled |[optional]
**ExecutionDetails** | [**MessagingV1BroadcastExecutionDetails**](MessagingV1BroadcastExecutionDetails.md) | |[optional]
**ErrorsFile** | **string** | Path to a file detailing errors from Broadcast execution |[optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# MessagingV1BroadcastExecutionDetails

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**TotalRecords** | **int** | Number of recipients in the Broadcast request |[optional]
**TotalCompleted** | **int** | Number of recipients with messages successfully sent to them |[optional]
**TotalErrors** | **int** | Number of recipients with messages unsuccessfully sent to them, producing an error |[optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


15 changes: 15 additions & 0 deletions rest/previewmessaging/v1/docs/MessagingV1CreateMessagesResult.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# MessagingV1CreateMessagesResult

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**TotalMessageCount** | **int** | The number of Messages processed in the request, equal to the sum of success_count and error_count. |[optional]
**SuccessCount** | **int** | The number of Messages successfully created. |[optional]
**ErrorCount** | **int** | The number of Messages unsuccessfully processed in the request. |[optional]
**MessageReceipts** | [**[]MessagingV1MessageReceipt**](MessagingV1MessageReceipt.md) | |[optional]
**FailedMessageReceipts** | [**[]MessagingV1FailedMessageReceipt**](MessagingV1FailedMessageReceipt.md) | |[optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


14 changes: 14 additions & 0 deletions rest/previewmessaging/v1/docs/MessagingV1Error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# MessagingV1Error

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Code** | **int** | The Twilio error code |[optional]
**Message** | **string** | The error message details |[optional]
**Status** | **int** | The HTTP status code |[optional]
**MoreInfo** | **string** | More information on the error |[optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


13 changes: 13 additions & 0 deletions rest/previewmessaging/v1/docs/MessagingV1FailedMessageReceipt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# MessagingV1FailedMessageReceipt

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**To** | **string** | The recipient phone number |[optional]
**ErrorMessage** | **string** | The description of the error_code |[optional]
**ErrorCode** | **int** | The error code associated with the message creation attempt |[optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


13 changes: 13 additions & 0 deletions rest/previewmessaging/v1/docs/MessagingV1Message.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# MessagingV1Message

## Properties

Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**To** | **string** | The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format for SMS/MMS or [Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses) for other 3rd-party channels. |[optional]
**Body** | **string** | The text of the message you want to send. Can be up to 1,600 characters in length. Overrides the request-level body and content template if provided. |[optional]
**ContentVariables** | **map[string]string** | Key-value pairs of variable names to substitution values. Refer to the [Twilio Content API Resources](https://www.twilio.com/docs/content-api/content-api-resources#send-a-message-with-preconfigured-content) for more details. |[optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


Loading
Loading