Skip to contentSkip to navigationSkip to topbar
On this page

Programmable Messaging Quickstart - Go


(information)

Info

Ahoy there! All messaging transmitted using Twilio's messaging channels is treated as Application-to-Person (A2P) messaging and subject to Twilio's Messaging Policy(link takes you to an external page). For detailed information on policy rules to ensure you remain compliant while using Twilio's services, please see our Acceptable Use Policy(link takes you to an external page).

With just a few lines of code, your Go application can send and receive text messages with Twilio Programmable Messaging.

This Go SMS Quickstart will teach you how to do this using our Programmable Messaging REST API and the Twilio Go helper library.

In this Quickstart, you will learn how to:

  1. Sign up for Twilio and get your first SMS-enabled Twilio phone number
  2. Set up your development environment to send and receive messages
  3. Send your first SMS
  4. Receive inbound text messages
  5. Reply to incoming messages with an SMS

Sign up for Twilio and Get a Twilio Phone Number

sign-up-for-twilio-and-get-a-twilio-phone-number page anchor
(information)

Info

If you already have a Twilio account and an SMS-enabled Twilio phone number, you're all set here! Feel free to jump to the next step.

(warning)

Warning

If you are sending SMS to the U.S. or Canada, before proceeding further please be aware of updated restrictions on the use of Toll-Free numbers for messaging, including TF numbers obtained through Free Trial. Please click here(link takes you to an external page) for details.

You can sign up for a free Twilio trial account here(link takes you to an external page).

  • When you sign up, you'll be asked to verify your personal phone number. This helps Twilio verify your identity and also allows you to send test messages to your phone from your Twilio account while in trial mode.
  • Once you verify your number, you'll be asked a series of questions to customize your experience.
  • Once you finish the onboarding flow, you'll arrive at your project dashboard in the Twilio Console(link takes you to an external page). This is where you'll be able to access your Account SID, authentication token, find a Twilio phone number, and more.

If you don't currently own a Twilio phone number with SMS functionality, you'll need to purchase one. After navigating to the Buy a Number(link takes you to an external page) page, check the SMS box and click Search.

Buy a twilio phone number.

You'll then see a list of available phone numbers and their capabilities. Find a number that suits your fancy and click Buy to add it to your account.

Select an SMS-enabled phone number.

Install Go and the Twilio Helper Library

install-go-and-the-twilio-helper-library page anchor
(information)

Info

If you've gone through one of our other Go Quickstarts already and have Go and the Twilio Go helper library installed, you can skip this step and get to the rest of the tutorial.

Before you can follow the rest of this tutorial, you'll need to have Go and the Twilio Go module installed.

Install Go

install-go page anchor

You can check if you already have Go installed on your machine by opening up a terminal and running the following command:

go version

You should see something like:

1
$ go version
2
go version go1.19 darwin/amd64

If you don't have Go installed, head over to go.dev and download the appropriate installer for your system(link takes you to an external page). Once you've installed Go, return to your terminal, and run the command above once again. If you don't see the installed Go version, you may need to relaunch your terminal.

Initialize your project and install the Twilio Go Helper Library

initialize-your-project-and-install-the-twilio-go-helper-library page anchor

Create a new Go project from your terminal using:

go mod init twilio-example

Once your project has been initialized, navigate into the newly created twilio-example directory and install the Twilio Go helper library module.

go get github.com/twilio/twilio-go

This will install the twilio-go module so that your Go code in the current directory can make use of it.


Send an outbound SMS message with Go

send-an-outbound-sms-message-with-go page anchor

Now that we have Go and the Twilio Go library installed, we can send an outbound text message from the Twilio phone number we just purchased with a single API request.

Create and open a new file called sendsms.go and type or paste in this code sample.

Send an SMS Using Twilio with GoLink to code sample: Send an SMS Using Twilio with Go
1
// Download the helper library from https://www.twilio.com/docs/go/install
2
package main
3
4
import (
5
"fmt"
6
"github.com/twilio/twilio-go"
7
api "github.com/twilio/twilio-go/rest/api/v2010"
8
"os"
9
)
10
11
func main() {
12
// Find your Account SID and Auth Token at twilio.com/console
13
// and set the environment variables. See http://twil.io/secure
14
// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
15
client := twilio.NewRestClient()
16
17
params := &api.CreateMessageParams{}
18
params.SetBody("This is the ship that made the Kessel Run in fourteen parsecs?")
19
params.SetFrom("+15017122661")
20
params.SetTo("+15558675310")
21
22
resp, err := client.Api.CreateMessage(params)
23
if err != nil {
24
fmt.Println(err.Error())
25
os.Exit(1)
26
} else {
27
if resp.Body != nil {
28
fmt.Println(*resp.Body)
29
} else {
30
fmt.Println(resp.Body)
31
}
32
}
33
}

Output

1
{
2
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
3
"api_version": "2010-04-01",
4
"body": "This is the ship that made the Kessel Run in fourteen parsecs?",
5
"date_created": "Thu, 24 Aug 2023 05:01:45 +0000",
6
"date_sent": "Thu, 24 Aug 2023 05:01:45 +0000",
7
"date_updated": "Thu, 24 Aug 2023 05:01:45 +0000",
8
"direction": "outbound-api",
9
"error_code": null,
10
"error_message": null,
11
"from": "+15017122661",
12
"num_media": "0",
13
"num_segments": "1",
14
"price": null,
15
"price_unit": null,
16
"messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
17
"sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
18
"status": "queued",
19
"subresource_uris": {
20
"media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json"
21
},
22
"tags": {
23
"campaign_name": "Spring Sale 2022",
24
"message_type": "cart_abandoned"
25
},
26
"to": "+15558675310",
27
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json"
28
}

You'll need to edit your development environment a little more before your message will send:

Set your credentials as environment variables

set-your-credentials-as-environment-variables page anchor

You'll notice that this code's main function creates a new Twilio client using the twilio.NewRestClient method, but no credentials are passed to it directly. The Twilio Go helper checks to see if your credentials are available as environment variables, and automatically consumes them for you.

To get and set these credentials, first go to https://www.twilio.com/console(link takes you to an external page) and log in. On this page, you'll find your unique Account SID and Auth Token, which you'll need any time you send messages through the Twilio client like this. You can reveal your auth token by clicking Show:

How to show your Auth Token from the Twilio Console.

Copy each value, and set them as environment variables in your terminal with the following commands (replacing the placeholders with your own values):

1
export TWILIO_ACCOUNT_SID=<your-account-sid>
2
export TWILIO_AUTH_TOKEN=<your-auth-token>
(information)

Info

Check out how to set environment variables(link takes you to an external page) for more information or other platform-specific syntax.

Replace the "from" phone number

replace-the-from-phone-number page anchor

Remember that SMS-enabled phone number you bought just a few minutes ago? Go ahead and replace the existing call to params.SetFrom to use that number, making sure to use E.164 formatting:

[+][country code][phone number including area code]

Replace the "to" phone number

replace-the-to-phone-number page anchor

Replace the phone number in params.SetTo with your mobile phone number. This can be any phone number that can receive text messages, but it's a good idea to test with your own phone, so you can see the magic happen! As above, you should use E.164 formatting for this value.

Save your changes and run this script from your terminal:

go run sendsms.go

That's it! In a few moments, you should receive an SMS from your Twilio number on your phone.

(warning)

Warning

If you are on a Twilio Trial account, your outgoing SMS messages are limited to phone numbers that you have verified with Twilio. Phone numbers can be verified via your Twilio Console's Verified Caller IDs(link takes you to an external page).

To include media in your Twilio-powered text message, you need to make an addition to the code from before. This time, add the mediaUrl parameter by calling params.SetMediaUrl.

1
// Download the helper library from https://www.twilio.com/docs/go/install
2
package main
3
4
import (
5
"fmt"
6
"github.com/twilio/twilio-go"
7
api "github.com/twilio/twilio-go/rest/api/v2010"
8
"os"
9
)
10
11
func main() {
12
// Find your Account SID and Auth Token at twilio.com/console
13
// and set the environment variables. See http://twil.io/secure
14
// Make sure TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN exists in your environment
15
client := twilio.NewRestClient()
16
17
params := &api.CreateMessageParams{}
18
params.SetBody("This is the ship that made the Kessel Run in fourteen parsecs?")
19
params.SetFrom("+15017122661")
20
params.SetTo("+15558675310")
21
params.SetMediaUrl([]string{
22
"https://c1.staticflickr.com/3/2899/14341091933_1e92e62d12_b.jpg",
23
})
24
25
resp, err := client.Api.CreateMessage(params)
26
if err != nil {
27
fmt.Println(err.Error())
28
os.Exit(1)
29
} else {
30
if resp.Body != nil {
31
fmt.Println(*resp.Body)
32
} else {
33
fmt.Println(resp.Body)
34
}
35
}
36
}

Output

1
{
2
"account_sid": "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
3
"api_version": "2010-04-01",
4
"body": "This is the ship that made the Kessel Run in fourteen parsecs?",
5
"date_created": "Thu, 24 Aug 2023 05:01:45 +0000",
6
"date_sent": "Thu, 24 Aug 2023 05:01:45 +0000",
7
"date_updated": "Thu, 24 Aug 2023 05:01:45 +0000",
8
"direction": "outbound-api",
9
"error_code": null,
10
"error_message": null,
11
"from": "+15017122661",
12
"num_media": "0",
13
"num_segments": "1",
14
"price": null,
15
"price_unit": null,
16
"messaging_service_sid": "MGaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
17
"sid": "SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
18
"status": "queued",
19
"subresource_uris": {
20
"media": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Media.json"
21
},
22
"tags": {
23
"campaign_name": "Spring Sale 2022",
24
"message_type": "cart_abandoned"
25
},
26
"to": "+15558675310",
27
"uri": "/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Messages/SMaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.json"
28
}

Again, update the from and to parameters to use your Twilio phone number and your mobile phone.

The new mediaUrl parameter in this code tells Twilio where to go to get the media we want to include. This must be a publicly accessible URL: Twilio will not be able to reach any URLs that are hidden or that require authentication.

Just as when you send a text-only SMS, Twilio will send data about the message in its response to your request. The JSON response will contain the unique SID and URI for your media resource:

"subresource_uris": {"media": "/2010-04-01/Accounts/ACxxxxxxxx/Messages/SMxxxxxxxxxxxxx/Media.json"}

When the Twilio REST API creates your new Message resource, it will save the image found at the specified mediaUrl as a Media resource. Once created, you can access this resource at any time via the API.

You can print this value from your Go code to see where the image is stored. Update your sendsms.go file's fmt.Println to see your newly provisioned Media URI(s):

1
for k, v := range *resp.SubresourceUris {
2
fmt.Println(k + ": " + v.(string))
3
}

Save the file and run your project. In just a moment, you will receive a text message with an image and see your new Media URI printed to your console.


Receive and reply to inbound SMS messages with Go and Gin

receive-and-reply-to-inbound-sms-messages-with-go-and-gin page anchor

When your Twilio number receives an incoming message, Twilio will send an HTTP request to a server you control. This callback mechanism is known as a webhook. When Twilio sends your application a request, it expects a response in the TwiML XML format telling it how to respond to the message. Let's see how we would build this in Go using the Gin framework(link takes you to an external page).

On the command line in your current directory, run the following command:

go get -u github.com/gin-gonic/gin

Create a file called server.go and use the following code to create a server that can handle incoming messages.

1
const express = require('express');
2
const { MessagingResponse } = require('twilio').twiml;
3
4
const app = express();
5
6
app.post('/sms', (req, res) => {
7
const twiml = new MessagingResponse();
8
9
twiml.message('The Robots are coming! Head for the hills!');
10
11
res.type('text/xml').send(twiml.toString());
12
});
13
14
app.listen(3000, () => {
15
console.log('Express server listening on port 3000');
16
});

Run this server with the following command:

go run server.go

You'll see that the server starts up on port 3000.

Before Twilio can send your application webhook requests, you'll need to make your application accessible over the Internet. While you can do that in any number of ways, we recommend using the Twilio CLI during local development. We'll show you how to set that up next so your app can receive messages.


macOSWindowsLinux

The suggested way to install twilio-cli on macOS is to use Homebrew(link takes you to an external page). If you don't already have it installed, visit the Homebrew site(link takes you to an external page) for installation instructions and then return here.

Once you have installed Homebrew, run the following command to install twilio-cli:

brew tap twilio/brew && brew install twilio
(information)

Info

For other installation methods, see the Twilio CLI Quickstart.

Run twilio login to get the Twilio CLI connected to your account.

You will need your Account SID and Auth Token once more in order to log in. Visit https://www.twilio.com/console(link takes you to an external page) and repeat the steps from earlier to get these values for the CLI.

Now, you can use the CLI to connect your phone number to your Go app.

Configure Your Webhook URL

configure-your-webhook-url page anchor

Now, you need to configure your Twilio phone number to call your webhook URL whenever a new message comes in. Just run this CLI command, replacing the phone number with your Twilio phone number:

twilio phone-numbers:update "+15017122661" --sms-url="http://localhost:3000/sms"
(information)

What's happening here?

We're using the Twilio CLI to set the SMS webhook URL for your phone number. Twilio will make a request to this URL whenever a new SMS message is received. The CLI is also using ngrok(link takes you to an external page) to create a tunnel to allow Twilio to reach your local development server (aka localhost).

You can also use the Twilio console(link takes you to an external page) to set a webhook in your web browser, but you will have to start up ngrok yourself(link takes you to an external page).

Make sure you are running on the command line (in separate tabs) both go run server.go and your twilio command.

With both of those servers running, we're ready for the fun part - testing our new Gin application!

Send an SMS from your mobile phone to your Twilio phone number that's configured with this webhook. You should see an HTTP request in your ngrok console. Your Gin app will process the text message, and you'll get your response back as an SMS.


Now that you know the basics of sending and receiving SMS and MMS text messages with Go, you might want to check out these resources.

Happy hacking!

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.