DEV Community

menarayanzshrestha
menarayanzshrestha

Posted on

Send Sms with Twilio on golang

Twilio is an American cloud communications platform. Working with golang is easier with twilio.

Lets signup for twilio account: Twilio | Try Twilio Free

Enter the details and get the account. Please verify your email and your mobile number with the flow of the link. We need three things to work with twilio on golang from Project Info.

  1. AUTH SID
  2. AUTH TOKEN
  3. PHONE NUMBER( Sender phone number)

Generate all these variable which are required for twilio api.

Let code some golang for integration with twilio:

First run this command to create go.mod

go mod init github.com/menarayanzshrestha/workwithtwilio

and create a file main.go

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, Golang Dev"))
    })

    PORT := "5000"

    fmt.Println("Serverr running on port:", PORT)

    http.ListenAndServe(":"+PORT, nil)

}
Enter fullscreen mode Exit fullscreen mode

Run this code and make sure the server is running. If you wake to work with hot reload follow the article on

Since we have to save the auth variables on code which is not a good practice. So let us integrate to pull the variables from .env file

Run this command to get the package.

go get -u github.com/joho/godotenv

And create the folder on root file named utils and under it create a file named “env.go”

package utils

import (
    "log"
    "os"

    "github.com/joho/godotenv"
)

//GetEnvWithKey : get env value of provided key
func GetEnvWithKey(key string) string {
    return os.Getenv(key)
}

//LoadEnv loads environment variables from .env file
func LoadEnv() {
    err := godotenv.Load(".env")
    if err != nil {
        log.Fatalf("Error loading .env file")
        os.Exit(1)
    }

}
Enter fullscreen mode Exit fullscreen mode

Now add this code on the main.go on the top of main function

utils.LoadEnv()
This will load the .env file

Lets make .env file in root

#twilio
SID=AC0e05cb5549fbc7ebbebf577*****
AUTH_TOKEN=aeb3c88f1306799550af2c*****
TWILIO_NO=+170888*****
Enter fullscreen mode Exit fullscreen mode

Note: This is just a sample value. You need to get them from twilio dashboard.

Now create a file “twilio.go” under utils folder

package utils

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "net/url"
    "strings"
)

func SendSms(to string, message string) {

    getEnv := GetEnvWithKey

    // Set account keys & information
    accountSid := getEnv("SID")
    authToken := getEnv("AUTH_TOKEN")
    from := getEnv("TWILIO_NO")

    urlStr := "https://api.twilio.com/2010-04-01/Accounts/" + accountSid + "/Messages.json"

    msgData := url.Values{}
    msgData.Set("To", to)
    msgData.Set("From", from)
    msgData.Set("Body", message)
    msgDataReader := *strings.NewReader(msgData.Encode())

    client := &http.Client{}
    req, _ := http.NewRequest("POST", urlStr, &msgDataReader)
    req.SetBasicAuth(accountSid, authToken)
    req.Header.Add("Accept", "application/json")
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

    resp, _ := client.Do(req)
    if resp.StatusCode >= 200 && resp.StatusCode < 300 {
        var data map[string]interface{}
        decoder := json.NewDecoder(resp.Body)
        err := decoder.Decode(&data)
        if err == nil {
            fmt.Println(data["sid"])
        }
        log.Print("------------Sent sms successfully------------")
    } else {
        fmt.Println(resp.Status)
    }
}
Enter fullscreen mode Exit fullscreen mode

Now we need to run the SendSms function in main.go. So add this inside “/ “ HandleFunc.

utils.SendSms("+9779800000000", "Test Message from twilio")

Note: “9800000000”is just the sample phone number . You need to verify the number first before able to send sms in trial version.

So lets start the server and hit http://localhost:5000

Hope it works.

Happy coding.

Top comments (0)