Hey there, fellow Go enthusiasts! Ready to dive into the world of Amazon SNS? You're in for a treat. We'll be using the github.com/aws/aws-sdk-go-v2/service/sns
package to build a robust integration that'll have you publishing and subscribing like a pro in no time.
Before we jump in, make sure you've got:
Let's kick things off:
mkdir sns-integration && cd sns-integration go mod init sns-integration go get github.com/aws/aws-sdk-go-v2/service/sns
You've got options here:
Environment variables:
export AWS_ACCESS_KEY_ID=your-access-key export AWS_SECRET_ACCESS_KEY=your-secret-key
AWS credentials file:
~/.aws/credentials
IAM roles (if you're on an EC2 instance)
Pick your poison, but remember: never commit your credentials to version control!
Time to get our hands dirty:
package main import ( "context" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sns" ) func main() { cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { // Handle error } client := sns.NewFromConfig(cfg) // You're ready to rock! }
result, err := client.CreateTopic(context.TODO(), &sns.CreateTopicInput{ Name: aws.String("MyAwesomeTopic"), }) if err != nil { // Handle error } topicArn := result.TopicArn
_, err = client.Publish(context.TODO(), &sns.PublishInput{ Message: aws.String("Hello, SNS world!"), TopicArn: topicArn, })
_, err = client.Subscribe(context.TODO(), &sns.SubscribeInput{ Protocol: aws.String("email"), TopicArn: topicArn, Endpoint: aws.String("[email protected]"), })
_, err = client.Publish(context.TODO(), &sns.PublishInput{ Message: aws.String("Hello with attributes!"), TopicArn: topicArn, MessageAttributes: map[string]types.MessageAttributeValue{ "AttributeName": { DataType: aws.String("String"), StringValue: aws.String("AttributeValue"), }, }, })
Set up subscription filter policies to receive only the messages you want. Trust me, your inbox will thank you.
Enable CloudWatch Logs for your SNS topics to keep tabs on message delivery. It's like a tracking number for your messages!
Unit tests are great, but don't forget integration tests. They'll save you from those "but it works on my machine" moments.
And there you have it! You're now equipped to build a solid Amazon SNS integration in Go. Remember, the AWS SDK documentation is your friend for diving deeper into any of these topics.
Now go forth and publish those messages! Your microservices are waiting.