-
Notifications
You must be signed in to change notification settings - Fork 0
/
alert.go
87 lines (71 loc) · 1.6 KB
/
alert.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"bytes"
"context"
"fmt"
"github.com/antonholmquist/jason"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"net/http"
"os"
)
type Slack struct {
WebhookURL string
Channel string
Name string
Message string
}
func send(s Slack) {
jsonStr := `{"channel":"` + s.Channel +
`","username":"` + s.Name +
`","text":"` + s.Message + `"}`
req, err := http.NewRequest(
"POST",
s.WebhookURL,
bytes.NewBuffer([]byte(jsonStr)),
)
if err != nil {
fmt.Print(err)
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Print(err)
}
fmt.Print(resp)
defer resp.Body.Close()
}
func createMessage(message string) string {
json, err := jason.NewObjectFromBytes([]byte(message))
if err != nil {
panic(err)
}
text := "<!channel>\n```\n"
for k, v := range json.Map() {
s, sErr := v.String()
if sErr == nil {
text += fmt.Sprintf("%s\t:%s\n", k, s)
} else {
text += fmt.Sprintf("%s\t:%s\n", k, sErr)
}
}
text += "```"
return text
}
// Send Slack notification from SNS event.
func slackNotice(ctx context.Context, snsEvent events.SNSEvent) {
fmt.Printf("events %s \n", snsEvent.Records)
for _, record := range snsEvent.Records {
snsRecord := record.SNS
fmt.Printf("[%s %s] Message = %s \n", record.EventSource, snsRecord.Timestamp, snsRecord.Message)
var s = Slack{os.Getenv("SLACK_WEBHOOK_URL"),
os.Getenv("SLACK_CHANNEL"),
os.Getenv("SLACK_NAME"),
createMessage(snsRecord.Message)}
send(s)
}
}
func main() {
lambda.Start(slackNotice)
}