-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
115 lines (95 loc) · 2.3 KB
/
main.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"encoding/json"
"bytes"
"log"
"net/http"
"fmt"
"time"
"os"
"sync"
)
type Configuration struct {
SlackWorkspaces SlackWorkspaces `json:"slackWorkspaces"`
Websites []string `json:"websites"`
}
type SlackWorkspaces []Slack
type Slack struct {
Endpoint string `json:"endpoint"`
Channel string `json:"channel"`
Username string `json:"username"`
IconEmoji string `json:"icon_emoji"`
}
type SlackMessage struct {
Channel string `json:"channel"`
Text string `json:"text"`
Username string `json:"username"`
IconEmoji string `json:"icon_emoji"`
}
func (s Slack) Send(message string) {
jsonData, _ := json.Marshal(SlackMessage{
Channel: s.Channel,
Text: message,
Username: s.Username,
IconEmoji: s.IconEmoji,
})
http.Post(s.Endpoint, "application/json", bytes.NewBuffer(jsonData))
}
var slackWorkspaces SlackWorkspaces
func checkWebsite(url string) bool {
client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
req.Header.Set("ignore-geo", "true")
resp, err := client.Do(req)
if err != nil {
return false
}
return resp.StatusCode == http.StatusOK
}
func sendWebsiteCrashAlert(url string) {
for _, slack := range slackWorkspaces {
slack.Send(fmt.Sprintf(":fire::fire::fire: %s is offline! :fire::fire::fire:", url))
}
}
func sendWebsiteBackUpAlert(url string) {
for _, slack := range slackWorkspaces {
slack.Send(fmt.Sprintf(":male-firefighter: %s is back online! :female-firefighter:", url))
}
}
func monitorWebsite(website string) {
isRunning := true
for {
wasRunning := isRunning
isRunning = checkWebsite(website)
if wasRunning && !isRunning {
sendWebsiteCrashAlert(website)
} else if !wasRunning && isRunning {
sendWebsiteBackUpAlert(website)
}
time.Sleep(1 * time.Minute)
}
}
func loadConfiguration() Configuration {
var configuration Configuration
file, err := os.Open("./config.json")
if err != nil {
log.Fatal(err)
}
decoder := json.NewDecoder(file)
err = decoder.Decode(&configuration)
if err != nil {
log.Fatal(err)
}
return configuration
}
func main() {
configuration := loadConfiguration()
slackWorkspaces = configuration.SlackWorkspaces
websites := configuration.Websites
var wg sync.WaitGroup
wg.Add(1)
for _, website := range websites {
go monitorWebsite(website)
}
wg.Wait()
}