Publish to SNS With Golang
SNS is a notification service. A user can send a notification to a topic. Each topic can have multiple subscribers, which receive a copy of every message sent to the topic – something like an HTTP endpoint, an email address, or an Amazon SQS queue. Sending a single notification can go to multiple places.
Steps to publish an SNS message on an Amazon SNS Topic
- An AWS Account to set up an SNS topic and 1 queue that receives from the topic you just created.
- Place your key and secret in your .aws/credentials file [http://docs.aws.amazon.com/AWSImportExport/latest/DG/SaveCredentials.html]
- Use GoLang 1.7+ [https://golang.org/doc/install
- Set your GOPATH [https://golang.org/doc/install#install]
- Install Amazon Core and SNS libraries
- go get github.com/aws/aws-sdk-go/aws
- go get github.com/aws/aws-sdk-go/aws/session
- go get github.com/aws/aws-sdk-go/service/sn
Create an AwsSns.go file (Code Explained below)
package main import ( "encoding/json" "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sns" _ "github.com/lib/pq" "github.com/spf13/cast" "github.com/spf13/viper" )
SnS JSON Struct Model
type SnsStruct struct { Type string `json:"type"` Title string `json:"title"` Model map[string]string `json:"model"` }
Main Function to Call Publish Sns Notification Message
func main(){ var sns SnsStruct sns.Type = Type sns.title= test SNSMap := make(map[string]string) SNSMap["Description"] = "test" sns.Model = SNSMap fmt.Println("Input: ", sns) fmt.Println("Output:",PublishSns(sns,"SNS_Topic_Name")) }
Publish Sns Function Thought Send Notification Message to topic
func PublishSns(message SnsStruct, topic string) string { //marshal the struct to json snsMessage, err := json.Marshal(message) if err != nil { return "Failed! Json Invaild" } fmt.Println("SNS MESSAGE to be sent ", string(snsMessage)) topicArn := "arn:aws:sns:ap-south-1:<topicArnNumber>:<topicName>" region := "SNS_REGION" sess, err := session.NewSession(&aws.Config{ Region: aws.String(region), }) if err != nil { return "Error creating SNS session" } svc := sns.New(sess) params := &sns.PublishInput{ Message: aws.String(string(snsMessage)),// This is the message itself (can be XML / JSON / Text - anything you want) TopicArn: aws.String(topicArn),//Get this from the Topic in the AWS console. } resp, err := svc.Publish(params) //Call to publish the message if err != nil { return "Error Call to publish message" + cast.ToString(err) } return "Success" }
Thank you for the nice article here. Really nice and keep update to explore more health and safety tips and ideas. Nebosh Courses In Chennai Nebosh IGC Course in Chennai International Safety Courses
ReplyDelete