-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
71 lines (56 loc) ยท 1.5 KB
/
Copy pathmain.go
File metadata and controls
71 lines (56 loc) ยท 1.5 KB
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
package main
import (
"context"
"fmt"
"os"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/sns"
)
var (
topicArn = os.Getenv("TOPIC_ARN")
client *sns.Client
)
func exitErrorf(msg string, args ...interface{}) {
fmt.Fprintf(os.Stderr, msg+"\n", args...)
os.Exit(1)
}
func sendNotification(ctx context.Context, message string) error {
fmt.Println("Sending notification to SNS...")
_, err := client.Publish(ctx, &sns.PublishInput{
Message: &message,
TopicArn: &topicArn,
})
if err != nil {
return fmt.Errorf("failed to send the message, %w", err)
}
fmt.Println("The notification was sent to SNS successfully!")
return nil
}
func lambdaHandler(ctx context.Context, dynamodbEvent events.DynamoDBEvent) error {
for _, record := range dynamodbEvent.Records {
if record.EventName == "INSERT" {
fmt.Println("A new message has arrived!")
if value, ok := record.Change.NewImage["URL"]; ok {
err := sendNotification(ctx, value.String())
if err != nil {
return fmt.Errorf("error sending notification to SNS, %w", err)
}
}
} else {
fmt.Println("New changes in DynamoDB, but no new message!")
}
}
return nil
}
func main() {
fmt.Println("Initializing...")
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
exitErrorf("cannot load the AWS config: %v", err)
}
client = sns.NewFromConfig(cfg)
fmt.Println("Ready!")
lambda.Start(lambdaHandler)
}