-
Notifications
You must be signed in to change notification settings - Fork 8
/
webhook.go
67 lines (58 loc) · 1.32 KB
/
webhook.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
package notifications
import (
"bytes"
"encoding/json"
"net/http"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
)
type Notifywebhook struct {
url string
config viper.Viper
AllowedNotifs []string
Log log.Logger
}
type payload struct {
Type string `json:"type"`
Path string `json:"path,omitempty"`
}
func (n *Notifywebhook) FromConfig(config viper.Viper) {
n.config = config
n.url = config.GetString("url")
n.AllowedNotifs = config.GetStringSlice("notificationtypes")
}
func (n *Notifywebhook) Connect() bool {
if n.url != "" {
return true
} else {
return false
}
}
func (n Notifywebhook) Notify(title string, description string, notifType string, path string) bool {
var allowed bool = false
for _, notif := range n.AllowedNotifs {
if notif == notifType {
allowed = true
}
}
if allowed {
data := payload{Type: notifType, Path: path}
payloadBytes, err := json.Marshal(data)
if err != nil {
n.Log.Error(err.Error())
}
body := bytes.NewReader(payloadBytes)
req, err := http.NewRequest("POST", n.url, body)
if err != nil {
n.Log.Error(err.Error())
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
n.Log.Error(err.Error())
}
defer resp.Body.Close()
return true
}
return false
}