Back to Blog
Integration Guides

How to Send SMS with Twilio and Go: Step-by-Step Tutorial

Use the Twilio Go helper library to send SMS from your Go application with proper error handling, retries, and status callback support.

DA
Danial A
Senior Twilio Consultant, Telphi Consulting
June 22, 2026
7 min read
Twilio
Integration
SDK
Mobile
How to Send SMS with Twilio and Go: Step-by-Step Tutorial

Twilio SMS and Go integrate through the official Twilio Go helper library, which wraps the Twilio REST API with typed structs and idiomatic Go error handling, letting you send SMS from any Go service, HTTP handler, or background worker with a few lines of code. This approach is used by backend engineering teams building microservices, CLI tools, or API servers in Go that need to dispatch SMS for alert notifications, system event reports, OTP delivery, or user communication, and who want a strongly-typed SDK that fits naturally into Go's error return convention and struct-based configuration pattern. The Twilio Go library is installed with go get, initialized with credentials loaded from environment variables using os.Getenv, and used to call twilio.NewRestClient().Api.CreateMessage to dispatch SMS and inspect the returned MessageResponse for the message SID and delivery status.

What You Need Before You Start

Install Go 1.21 or later on your development machine and initialize your Go module with go mod init your-module-name. Install the Twilio Go helper library by running go get github.com/twilio/twilio-go in your project directory, which adds the dependency to go.mod and downloads the package. Collect your Twilio Account SID, Auth Token, and a provisioned SMS-capable phone number from the Twilio Console. Store credentials in environment variables by setting TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, and TWILIO_FROM_NUMBER in your shell profile, .env file loaded by godotenv, or your deployment platform's secret management system. Never assign credential strings as Go constants or var declarations in source files that are committed to version control, as they would be visible in git history.

Step-by-Step Integration Guide

In your Go source file, import github.com/twilio/twilio-go and github.com/twilio/twilio-go/rest/api/v2010. Retrieve credentials with os.Getenv and construct the client using twilio.NewRestClientWithParams passing a twilio.ClientParams struct with Username set to the Account SID and Password set to the Auth Token. Define a SendSMS function that accepts toPhone and body strings and returns a string SID and error, creating an ApiV2010CreateMessageParams struct with To, From, and Body fields set to the respective values. Call client.Api.CreateMessage with the params, check if the returned error is non-nil and return an empty string and the error if so, otherwise dereference resp.Sid with a nil check and return it. In your HTTP handler or main function, call SendSMS, handle the returned error with a log.Printf and an appropriate HTTP response status, and write the SID to the response body as JSON using encoding/json. Add context support by passing a context.Context to the Twilio client call using the WithContext method available on the params struct for timeout and cancellation propagation.

Common Issues and How to Fix Them

The Twilio Go client returns an error with message 'unable to create record: 20003 Authentication Error' when os.Getenv returns an empty string because the environment variable is not set in the current process, which happens when the variable is exported in one terminal session but the Go program runs in a different process or a fresh shell. Add an explicit startup check that calls os.Getenv for each required credential variable and calls log.Fatal with a descriptive message if any returns an empty string, so the program fails loudly at startup rather than silently failing on the first SMS attempt. The CreateMessage call returns a REST error with code 21614 when the destination number is not a mobile number capable of receiving SMS, which blocks delivery to landlines. Add a Twilio Lookup API call before dispatching SMS to verify the line type of the destination number, checking the line_type_intelligence field for mobile or voip and skipping the SMS dispatch if the number is a landline, returning a descriptive error to the caller. The Go HTTP server panics with a nil pointer dereference when resp.Sid is dereferenced without checking for nil, because the Twilio Go library returns pointer fields that may be nil on partial API responses. Always check resp.Sid != nil before dereferencing and return an error with message 'no message SID returned' when the pointer is nil.

How to Get More from This Integration

Build a Go SMS worker using goroutines by defining a channel of type chan SMSJob where SMSJob is a struct containing ToPhone and Body, spawning a pool of goroutine workers that each read from the channel and call SendSMS, and exposing an HTTP handler that pushes jobs to the channel and immediately returns 202 Accepted, decoupling message dispatch from the HTTP request lifecycle and allowing concurrent SMS sending up to your Twilio account's throughput limit. Add status callback handling by registering a POST /sms-status Go HTTP handler that reads Twilio's status callback POST body parameters MessageSid and MessageStatus, updates a database record keyed by MessageSid with the new status, and returns HTTP 200 to prevent Twilio retries, enabling per-message delivery tracking without polling. Integrate Twilio Messaging Services for geographic routing by replacing the From field in CreateMessageParams with MessagingServiceSid set to your Messaging Service SID from the Twilio Console, letting the Messaging Service automatically select the optimal sender number for the destination country based on the copilot configuration you set in the Console.

Conclusion

Go and Twilio together provide a high-performance, strongly-typed SMS dispatch layer that fits naturally into Go's error handling idioms and concurrency model. Contact Telphi Consulting to design and build the Twilio SMS microservice for your Go application.

Share this article:
0 views

Ready to Transform Your Business Communications?

Get a free consultation with our VoIP experts and discover how we can help you save costs, improve efficiency, and scale your business.

Comments (0)

Join the discussion and share your thoughts (AI-moderated for quality)

Protected by AI moderation

Be the first to comment

No comments yet. Share your thoughts below.