Use the official go-twilio client library to authenticate with your Account SID and Auth Token, then call the appropriate service methods (like CreateMessage) to interact with Twilio resources. This approach handles HTTP requests, JSON serialization, and error handling automatically, saving you from writing raw REST calls.
First, install the library via go get, then initialize the client with your credentials. For sending an SMS, you simply instantiate a Client and call CreateMessage with the To, From, and Body parameters.
// Install the library:
// go get github.com/twilio/twilio-go
package main
import (
"fmt"
"log"
"github.com/twilio/twilio-go"
openapi "github.com/twilio/twilio-go/rest/api/v2010"
)
func main() {
// Replace with your actual credentials from the Twilio Console
accountSID := "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
authToken := "your_auth_token"
client := twilio.NewRestClient()
client.SetAuthCredentials(accountSID, authToken)
// Create a message
msg, err := client.CreateMessage(&openapi.CreateMessageParams{
To: twilio.String("+15558675309"),
From: twilio.String("+15551234567"), // Must be a verified Twilio number
Body: twilio.String("Hello from Go!"),
})
if err != nil {
log.Fatalf("Error creating message: %v", err)
}
fmt.Printf("Message SID: %s\n", *msg.Sid)
}
For more complex interactions, like looking up phone numbers or managing call records, you use the same client instance but switch to the specific resource manager. For example, to fetch a phone number's details:
// Fetch a phone number record
num, err := client.GetPhoneNumber("+15551234567")
if err != nil {
log.Fatalf("Error fetching number: %v", err)
}
fmt.Printf("Number Status: %s\n", *num.Status)
Always store your Account SID and Auth Token in environment variables rather than hardcoding them in your source files to prevent security leaks. You can load them easily using os.Getenv("TWILIO_ACCOUNT_SID") and os.Getenv("TWILIO_AUTH_TOKEN"). If you encounter rate limits or network timeouts, the client returns standard Go errors that you can inspect to retry or log appropriately. The library is actively maintained and covers the full Twilio API surface, including Voice, SMS, WhatsApp, and Verify.