/
notification.go
executable file
·72 lines (62 loc) · 1.77 KB
/
notification.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package common
import (
"encoding/json"
"github.com/aws/aws-sdk-go/service/sns"
"github.com/pkg/errors"
)
// Notificationer interface requires methods to interact with an AWS SNS Topic
// and publish a message to it
type Notificationer interface {
PublishMessage(topicArn *string, message *string, isJSON bool) (*string, error)
}
// SNS implements the Notification interface with AWS SNS SDK
type SNS struct {
Client *sns.SNS
}
// PublishMessage pushes the provided messeage to an SNS Topic and returns the
// messages' ID.
func (notif *SNS) PublishMessage(topicArn *string, message *string,
isJSON bool) (*string, error) {
// Create the SNS PublishInput
var publishInput *sns.PublishInput
if isJSON {
messageStructure := "json"
publishInput = &sns.PublishInput{
TopicArn: topicArn,
Message: message,
MessageStructure: &messageStructure,
}
} else {
publishInput = &sns.PublishInput{
TopicArn: topicArn,
Message: message,
}
}
// Publish the Message to the Topic
publishOutput, err := notif.Client.Publish(publishInput)
if err != nil {
return nil, err
}
return publishOutput.MessageId, err
}
// PrepareSNSMessageJSON creates a JSON message
// from a struct, for publising to an SNS topic
func PrepareSNSMessageJSON(body interface{}) (string, error) {
// Marshal the message body as JSON
bodyJSON, err := json.Marshal(body)
if err != nil {
return "", errors.Wrap(err, "Failed to prepare SNS body JSON")
}
// Wrap the body in a SNS message object
messageJSON, err := json.Marshal(struct {
Default string `json:"default"`
Body string `json:"Body"`
}{
Default: string(bodyJSON),
Body: string(bodyJSON),
})
if err != nil {
return "", errors.Wrap(err, "Failed to prepare SNS body JSON")
}
return string(messageJSON), nil
}