forked from reinbach/drone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook.go
59 lines (50 loc) · 1.25 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
package notify
import (
"bytes"
"encoding/json"
"net/http"
"github.com/drone/drone/pkg/model"
)
type Webhook struct {
URL []string `yaml:"urls,omitempty"`
Success bool `yaml:"on_success,omitempty"`
Failure bool `yaml:"on_failure,omitempty"`
}
func (w *Webhook) Send(context *Context) error {
switch {
case context.Commit.Status == "Success" && w.Success:
return w.send(context)
case context.Commit.Status == "Failure" && w.Failure:
return w.send(context)
}
return nil
}
// helper function to send HTTP requests
func (w *Webhook) send(context *Context) error {
// data will get posted in this format
data := struct {
Owner *model.User `json:"owner"`
Repo *model.Repo `json:"repository"`
Commit *model.Commit `json:"commit"`
}{context.User, context.Repo, context.Commit}
// data json encoded
payload, err := json.Marshal(data)
if err != nil {
return err
}
// loop through and email recipients
for _, url := range w.URL {
go sendJson(url, payload)
}
return nil
}
// helper fuction to sent HTTP Post requests
// with JSON data as the payload.
func sendJson(url string, payload []byte) {
buf := bytes.NewBuffer(payload)
resp, err := http.Post(url, "application/json", buf)
if err != nil {
return
}
resp.Body.Close()
}