I'm having issue with sending a message to SNS with the AWS Go SDK. Documentation for the Publish function is a little bit obscure.
My piece of code is:
package main
import (
"encoding/json"
"github.com/aws/aws-sdk-go-v2/aws/external"
"github.com/aws/aws-sdk-go-v2/service/sns"
"github.com/aws/aws-sdk-go/aws"
"log"
)
type Person struct {
Name string `json:"name"`
}
func main() {
cfg, _ := external.LoadDefaultAWSConfig()
snsClient := sns.New(cfg)
person := Person{
Name:"ok",
}
jsonStr, _ := json.Marshal(person)
req := snsClient.PublishRequest(&sns.PublishInput{
TopicArn: aws.String("arn:aws:sns:us-east-1:*****:ok"),
Message: aws.String(string(jsonStr)),
MessageStructure: aws.String("json"),
MessageAttributes: map[string]sns.MessageAttributeValue{
"default": {
DataType: aws.String("String"),
StringValue: aws.String(string(jsonStr)),
},
},
})
res, err := req.Send()
if err != nil {
log.Fatal(err)
}
log.Print(res)
}
When I launch this code I receive the following message :
2019/01/24 20:14:24 InvalidParameter: Invalid parameter: Message Structure - No default entry in JSON message body
status code: 400, request id: 55940de1-9645-5485-96c5-592586957ce8
exit status 1
Maybe someone can help me with that ?
Thanks
I've found a solution to my issue.
package main
import (
"encoding/json"
"github.com/aws/aws-sdk-go-v2/aws/external"
"github.com/aws/aws-sdk-go-v2/service/sns"
"github.com/aws/aws-sdk-go-v2/aws"
"log"
)
type Message struct {
Default string `json:"default"`
}
type Person struct {
Name string `json:"name"`
}
func main() {
cfg, _ := external.LoadDefaultAWSConfig()
snsClient := sns.New(cfg)
person := Person{
Name: "Felix Kjellberg",
}
personStr, _ := json.Marshal(person)
message := Message{
Default: string(personStr),
}
messageBytes, _ := json.Marshal(message)
messageStr := string(messageBytes)
req := snsClient.PublishRequest(&sns.PublishInput{
TopicArn: aws.String("arn:aws:sns:us-east-1:*****:ok"),
Message: aws.String(messageStr),
MessageStructure: aws.String("json"),
})
res, err := req.Send()
if err != nil {log.Fatal(err)
}
log.Print(res)
}
Some encoding inception was needed
You have to add a "default" field to your json payload for subscribers that can't consume your message payload. Take a look at this (towards the bottom): https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-custommessage.html