forked from awsdocs/aws-doc-sdk-examples
/
SubscribeTopic.go
70 lines (59 loc) · 2.3 KB
/
SubscribeTopic.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
// snippet-start:[sns.go.subscribe_topic]
package main
// snippet-start:[sns.go.subscribe_topic.imports]
import (
"flag"
"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/aws/aws-sdk-go/service/sns/snsiface"
)
// snippet-end:[sns.go.subscribe_topic.imports]
// SubscribeTopic subscribes a user to a topic by their email address
// Inputs:
// svc is an Amazon SNS service client
// email is the email address of the user
// topicARN is the ARN of the topic
// Output:
// If success, information about the subscription and nil
// Otherwise, nil and an error from the call to Subscribe
func SubscribeTopic(svc snsiface.SNSAPI, email, topicARN *string) (*sns.SubscribeOutput, error) {
// snippet-start:[sns.go.subscribe_topic.call]
result, err := svc.Subscribe(&sns.SubscribeInput{
Endpoint: email,
Protocol: aws.String("email"),
ReturnSubscriptionArn: aws.Bool(true), // Return the ARN, even if user has yet to confirm
TopicArn: topicARN,
})
// snippet-end:[sns.go.subscribe_topic.call]
return result, err
}
func main() {
// snippet-start:[sns.go.subscribe_topic.args]
email := flag.String("e", "", "The email address of the user subscribing to the topic")
topicARN := flag.String("t", "", "The ARN of the topic to which the user subscribes")
flag.Parse()
if *email == "" || *topicARN == "" {
fmt.Println("You must supply an email address and topic ARN")
fmt.Println("-e EMAIL -t TOPIC-ARN")
return
}
// snippet-end:[sns.go.subscribe_topic.args]
// snippet-start:[sns.go.subscribe_topic.session]
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := sns.New(sess)
// snippet-end:[sns.go.subscribe_topic.session]
result, err := SubscribeTopic(svc, email, topicARN)
if err != nil {
fmt.Println("Got an error subscribing to the topic:")
fmt.Println(err)
return
}
fmt.Println(*result.SubscriptionArn)
}
// snippet-end:[sns.go.subscribe_topic]