forked from qiniu/webhook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook.go
117 lines (89 loc) · 2.34 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
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
116
package main
import (
"log"
"os"
"os/exec"
"io/ioutil"
"net/url"
"net/http"
"encoding/json"
)
// --------------------------------------------------------------------------------
type WatchItem struct {
Repo string `json:"repo"`
Branch string `json:"branch"`
Script string `json:"script"`
}
type Config struct {
BindHost string `json:"bind"`
Items []WatchItem `json:"items"`
}
// --------------------------------------------------------------------------------
type Repository struct {
Url string `json:"url"` // "https://github.com/qiniu/api"
}
type Payload struct {
Ref string `json:"ref"` // "refs/heads/develop"
Repo Repository `json:"repository"`
}
// --------------------------------------------------------------------------------
func runScript(item *WatchItem) (err error) {
script := "./" + item.Script
out, err := exec.Command("bash", "-c", script).Output()
if err != nil {
log.Println("Exec command failed:", err)
}
log.Print("Run ", script, " output:\n", string(out))
return
}
func handleQuery(query url.Values, cfg *Config) (err error) {
payload := query.Get("payload")
b := []byte(payload)
var payloadObj map[string]interface{}
err = json.Unmarshal(b, &payloadObj)
if err != nil {
log.Println("json.Unmarshal payload failed:", err)
return
}
b, _ = json.MarshalIndent(payloadObj, "", " ")
text := string(b)
log.Println(text)
var event Payload
err = json.Unmarshal(b, &event)
if err != nil {
log.Println("json.Unmarshal payload failed:", err)
return
}
for _, item := range cfg.Items {
if event.Repo.Url == item.Repo && event.Ref == "refs/heads/" + item.Branch {
err = runScript(&item)
break
}
}
return
}
// --------------------------------------------------------------------------------
var cfg Config
func handle(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
handleQuery(req.Form, &cfg)
}
func main() {
if len(os.Args) < 2 {
println("Usage: webhook <ConfigFile>\n")
return
}
cfgbuf, err := ioutil.ReadFile(os.Args[1])
if err != nil {
log.Println("Read config file failed:", err)
return
}
err = json.Unmarshal(cfgbuf, &cfg)
if err != nil {
log.Println("Unmarshal config failed:", err)
return
}
http.HandleFunc("/", handle)
log.Fatal(http.ListenAndServe(cfg.BindHost, nil))
}
// --------------------------------------------------------------------------------