Introducing Twilio's Go Helper Library

October 06, 2022
Written by
Reviewed by

twilio-go-helper

Whether you are building your first product with Twilio or looking to expand your product offering, you need access to tools in the programming languages or environments you use. Today, we are excited to announce that we have released a Go Helper for every Twilio API built using OpenAPI.

For a long time we’ve supported and maintained helper libraries and tooling in the most popular languages and environments used by developers. We’re now expanding that coverage by providing a Twilio Helper for Go.

To get started, check out our getting started guide.

Why use the Twilio Go Helper?

The Go library offers new functionality and takes advantage of modern language features. We’ve built it from the ground up based on developer feedback we received from you.

Here are a few reasons why we believe using an official Twilio Helper makes it safer and more efficient to build with Twilio.

  • Automatic serialization/deserialization – all the error, return, and request types are included in the SDK, so you don’t have to convert raw string/byte content into objects.
  • Authentication Logic – we provide logic to make it straightforward to authenticate with Twilio’s API.
  • Twilio API Endpoints – you can leverage all of Twilio APIs through the helper and extend your integration as you grow or build new features.
  • Request Validation – helps to ensure that incoming requests are actually coming from Twilio and not unknown actors.
  • Pagination Support – automatically handle pagination across collections, such as messages and calls.

Use cases

To get started with Go we have selected some quick examples to get you started with Go.

package main

import (
	"encoding/json"
	"fmt"
	"github.com/twilio/twilio-go"
	twilioApi "github.com/twilio/twilio-go/rest/api/v2010"
	"os"
)

func main() {
	from := os.Getenv("TWILIO_FROM_PHONE_NUMBER")
	to := os.Getenv("TWILIO_TO_PHONE_NUMBER")

	client := twilio.NewRestClient()

	params := &twilioApi.CreateMessageParams{}
	params.SetTo(to)
	params.SetFrom(from)
	params.SetBody("Hello from the Twilio Go Helper Library")

	resp, err := client.Api.CreateMessage(params)
	if err != nil {
		fmt.Println(err.Error())
	} else {
		response, _ := json.Marshal(*resp)
		fmt.Println("Response: " + string(response))
	}
}
package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/twilio/twilio-go/twiml"
)

func main() {
	r := gin.Default()

	r.POST("/sms", func(c *gin.Context) {
		var msg = &twiml.MessagingMessage{}

		// Get the message the user sent our Twilio number
		body := c.PostForm("Body")

		// Determine the right reply for the message
		if body == "hello" {
			msg.Body = "Hi!"
		} else if body == "bye" {
			msg.Body = "Goodbye"
		}

		// Generate and return our TwiML response
		twiml, _ := twiml.Messages([]twiml.Element{msg})
		c.Header("Content-Type", "text/xml")
		c.String(http.StatusOK, twiml)
	})

	r.Run()
}
package main

import (
	"fmt"
	"os"

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

func main() {
	// You can find your Auth Token at twilio.com/console
	// For this example: authToken := "12345"
	authToken := os.Getenv("TWILIO_AUTH_TOKEN")
	
	requestValidator := client.NewRequestValidator(authToken)

	// Twilio's request URL
	url := "https://mycompany.com/myapp.php?foo=1&bar=2"
	
	// Post variables in Twilio's request
	params := map[string]string{
		"CallSid": "CA1234567890ABCDE",
		"Caller":  "+12349013030",
		"Digits":  "1234",
		"From":    "+12349013030",
		"To":      "+18005551212",
	}
	
	// X-Twilio-Signature header attached to the request
	signature := "0/KCTR6DLpKmkAf8muzZqo1nDgQ="
    
	// Validate GET request
	fmt.Println(requestValidator.Validate(url, params, signature))

	// Example of the POST request
	Body := []byte(`{"property": "value", "boolean": true}`)
	theUrl := "https://mycompany.com/myapp.php?bodySHA256=0a1ff7634d9ab3b95db5c9a2dfe9416e41502b283a80c7cf19632632f96e6620"
	theSignature := "y77kIzt2vzLz71DgmJGsen2scGs="
    
	// Validate POST request
	fmt.Println(requestValidator.ValidateBody(theUrl, Body, theSignature))
}

For more examples, please check out our documentation.

Why Go?

Go solves a critical need for teams of developers, both small and large. A language that provides the speed, safety, scalability of a static language with the ease of use of a dynamic one.

In our use of Go at Twilio, we have seen that it can be useful for both high and low level programming. You can achieve both polymorphism and abstractions. You can also employ proper code refactorization to optimize memory layout for data structures and influence where a compiler will allocate the structure. You can use high-level channels, but when high performance is crucial, you can also use mutexes.

Try it out!

We can’t wait to see all the amazing things you’ll build with Twilio’s Go Helper! 🚀

If you want to provide feedback to our team, reach out to me via email at gjones[at]twilio.com.