Using Twilio Go SDK

You can inject a custom HTTP client with transport implementation that will overwrite the request URL for any SDK requests and point it to MessageBird Twilio Adapter endpoint.

Here is an example of such a transport implementation

package messagebird

package messagebird
import (
    "net/http"
    "time"
)

const (
    mbAddress = "us-west-1.twilio.to.nest.messagebird.com"
    scheme = "https"
)

func NewHTTPClient() *http.Client {
    return &http.Client{
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
        Timeout: time.Second * 10,
        Transport: &overwriteTransport{
        rt: http.DefaultTransport,
        },
    }
}

type overwriteTransport struct {
    rt http.RoundTripper
}

func (t *overwriteTransport) RoundTrip(r *http.Request) (*http.Response, error) {
    r.URL.Host = mbAddress
    r.URL.Scheme = scheme
    return t.rt.RoundTrip(r)
}

To use it with the Twilio Go SDK, all that is required is to inject the http.Client using overwriteTransport into the twilioClient using it’s constructor. As per the example on the Twilio repository readme:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/davecgh/go-spew/spew"
    "github.com/messagebird/twilio-test/internal/messagebird"
    "github.com/twilio/twilio-go"
    twilioClient "github.com/twilio/twilio-go/client"
    twilioApi "github.com/twilio/twilio-go/rest/api/v2010"
)

const (
    accountSid = "ACb2d7a01386df4aa782458f3715c87ae2"
    authToken = "mBFDCtxhxAGwpeQTqGpFsG6TcDCEL8Km0rTq"
)

func main() {
    client := twilio.NewRestClientWithParams(twilio.ClientParams{
        Client: &twilioClient.Client{
        Credentials: &twilioClient.Credentials{
            Username: accountSid,
            Password: authToken,
        },
        HTTPClient: messagebird.NewHTTPClient(),
        },
    })
    
    params := &twilioApi.CreateMessageParams{}
    params.SetTo("+44555555555")
    params.SetFrom("+355555555555)
    params.SetBody("Hello from Go!")
    
    resp, err := client.Api.CreateMessage(params)
    if err != nil {
        fmt.Println("Error sending SMS message: " + err.Error())
    } else {
        response, _
        := json.Marshal(*resp)
        fmt.Println("Response: " + string(response))
    }
    spew.Dump(resp, err)
}

Last updated