From c5e5b6e64c3d80dddfc8a93e88d2c4f354024b8f Mon Sep 17 00:00:00 2001 From: AsabuHere Date: Mon, 16 Oct 2023 19:55:39 +0530 Subject: [PATCH] Add support for serialization and deserialization of json payload --- client/client.go | 70 ++++++++++++++++++++------ rest/previewmessaging/v1/broadcasts.go | 22 +++----- rest/previewmessaging/v1/messages.go | 30 +++++------ 3 files changed, 78 insertions(+), 44 deletions(-) diff --git a/client/client.go b/client/client.go index 7db496a18..54de0af7f 100644 --- a/client/client.go +++ b/client/client.go @@ -5,13 +5,13 @@ import ( "encoding/json" "fmt" "net/http" + "bytes" "net/url" "regexp" "runtime" "strconv" "strings" "time" - "github.com/pkg/errors" "github.com/twilio/twilio-go/client/form" ) @@ -56,7 +56,27 @@ func (c *Client) SetTimeout(timeout time.Duration) { c.HTTPClient.Timeout = timeout } +func extractContentTypeHeader(headers map[string]interface{}) (cType string){ + headerType, ok := headers["Content-Type"] + if !ok { + return urlEncodedContentType + } + return headerType.(string) +} + +func decodeJsonPayload(jsonBody string)(s []byte){ + prefixTrimmedString := jsonBody[2:] + 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 = '\\' @@ -90,13 +110,18 @@ func (c *Client) doWithErr(req *http.Request) (*http.Response, error) { // 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) { - u, err := url.Parse(rawURL) + modRawURL := "https://preview.messaging.twilio.com" + rawURL + + contentType := extractContentTypeHeader(headers) + + u, err := url.Parse(modRawURL) if err != nil { return nil, err } - + valueReader := &strings.Reader{} goVersion := runtime.Version() + var req *http.Request if method == http.MethodGet { if data != nil { @@ -108,13 +133,35 @@ func (c *Client) SendRequest(method string, rawURL string, data url.Values, } } - 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]) + encodedString, err = url.QueryUnescape(string(jsonData)) + 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 { + 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()) @@ -128,13 +175,6 @@ func (c *Client) SendRequest(method string, rawURL string, data url.Values, req.Header.Add("User-Agent", userAgent) - if method == http.MethodPost { - _, ok := headers["Content-Type"] - if !ok { - req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - } - } - for k, v := range headers { req.Header.Add(k, fmt.Sprint(v)) } diff --git a/rest/previewmessaging/v1/broadcasts.go b/rest/previewmessaging/v1/broadcasts.go index 543cc05c6..8d7fcb6d2 100644 --- a/rest/previewmessaging/v1/broadcasts.go +++ b/rest/previewmessaging/v1/broadcasts.go @@ -15,21 +15,17 @@ package openapi import ( - "encoding/json" - "fmt" - "net/url" - - "github.com/twilio/twilio-go/client" + "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){ +func (params *CreateBroadcastParams) SetXTwilioRequestKey(XTwilioRequestKey string) *CreateBroadcastParams { params.XTwilioRequestKey = &XTwilioRequestKey return params } @@ -37,15 +33,13 @@ func (params *CreateBroadcastParams) SetXTwilioRequestKey(XTwilioRequestKey stri // Create a new Broadcast func (c *ApiService) CreateBroadcast(params *CreateBroadcastParams) (*MessagingV1Broadcast, error) { path := "/v1/Broadcasts" - -data := url.Values{} -headers := make(map[string]interface{}) + data := url.Values{} + headers := make(map[string]interface{}) - - if params != nil && params.XTwilioRequestKey != nil { - headers["X-Twilio-Request-Key"] = *params.XTwilioRequestKey - } + 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 { diff --git a/rest/previewmessaging/v1/messages.go b/rest/previewmessaging/v1/messages.go index 8e810e7e5..cc54238b7 100644 --- a/rest/previewmessaging/v1/messages.go +++ b/rest/previewmessaging/v1/messages.go @@ -15,21 +15,17 @@ package openapi import ( - "encoding/json" - "fmt" - "net/url" - - "github.com/twilio/twilio-go/client" + "encoding/json" + "net/url" ) - // Optional parameters for the method 'CreateMessages' type CreateMessagesParams struct { // CreateMessagesRequest *CreateMessagesRequest `json:"CreateMessagesRequest,omitempty"` } -func (params *CreateMessagesParams) SetCreateMessagesRequest(CreateMessagesRequest CreateMessagesRequest) (*CreateMessagesParams){ +func (params *CreateMessagesParams) SetCreateMessagesRequest(CreateMessagesRequest CreateMessagesRequest) *CreateMessagesParams { params.CreateMessagesRequest = &CreateMessagesRequest return params } @@ -37,15 +33,19 @@ func (params *CreateMessagesParams) SetCreateMessagesRequest(CreateMessagesReque // Send messages to multiple recipients func (c *ApiService) CreateMessages(params *CreateMessagesParams) (*MessagingV1CreateMessagesResult, error) { path := "/v1/Messages" - -data := url.Values{} -headers := make(map[string]interface{}) - -if params != nil && params.CreateMessagesRequest != nil { - data.Set("CreateMessagesRequest", fmt.Sprint(*params.CreateMessagesRequest)) -} - + data := url.Values{} + headers := map[string]interface{}{ + "Content-Type": "application/json", + } + if params != nil && params.CreateMessagesRequest != nil { + v, err := json.Marshal(*params.CreateMessagesRequest) + if err != nil { + return nil, err + } + urlEncodedData := url.QueryEscape(string(v)) + data.Set("CreateMessagesRequest", urlEncodedData) + } resp, err := c.requestHandler.Post(c.baseURL+path, data, headers) if err != nil {