Introduction

Sending SMS messages is a powerful feature for applications, enabling direct communication with users for various purposes such as notifications, alerts, and security verifications. AWS Simple Notification Service (SNS) provides a flexible and scalable way to send SMS messages. This guide will demonstrate how to send SMS messages using the AWS SDK for Go, including example code and how to perform unit tests.

Prerequisites

  • AWS Account: You must have an active AWS account. If you don't, sign up at AWS.
  • Go Environment: Ensure Go is installed on your development machine. If it's not, download it from Go's official site.
  • AWS CLI: Install and configure the AWS CLI with the necessary permissions. Follow the AWS CLI Setup Guide.

Step 1: Setting Up Your Go Project

Create a new directory for your Go project and initialize a Go module:

mkdir aws-sms-go
cd aws-sms-go
go mod init aws-sms-go

Install the AWS SDK for Go v2:

go get github.com/aws/aws-sdk-go-v2
go get github.com/aws/aws-sdk-go-v2/config
go get github.com/aws/aws-sdk-go-v2/service/sns

Step 2: Writing the SMS Sending Function

Create a new Go file named sendSms.go in your project directory. Add the following code to define a function for sending an SMS message:

package main

import (
    "context"
    "fmt"
    "log"
    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/sns"
)

func sendSms(phoneNumber string, message string) (*sns.PublishOutput, error) {
    cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion("us-east-1"))
    if err != nil {
        log.Fatalf("Unable to load SDK config, %v", err)
    }

    snsClient := sns.NewFromConfig(cfg)

    result, err := snsClient.Publish(context.TODO(), &sns.PublishInput{
        Message:     aws.String(message),
        PhoneNumber: aws.String(phoneNumber),
    })

    if err != nil {
        return nil, fmt.Errorf("failed to send message: %w", err)
    }

    return result, nil
}

func main() {
    // Example usage
    result, err := sendSms("+1234567890", "Hello from AWS SNS using Go!")
    if err != nil {
        log.Fatalf("Error: %s", err.Error())
    }
    fmt.Printf("Message sent with ID: %s\n", *result.MessageId)
}

Conclusion

Sending SMS messages using the AWS SDK for Go and AWS SNS is a straightforward process that can significantly enhance the capabilities of your Go applications. By following the steps outlined in this guide, you've learned how to set up your Go project, implement an SMS sending function, and prepare for unit testing. Effective error handling and secure management of AWS credentials are crucial for building reliable and secure applications.