-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
66 lines (55 loc) · 1.57 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
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/go-playground/webhooks/v6/github"
_ "github.com/joho/godotenv/autoload"
)
const (
path = "/webhooks"
)
var (
secret = os.Getenv("SECRET")
addr = os.Getenv("ADDR")
)
func init() {
if secret == "" {
log.Fatalf("[fatal] invalid secret: %+q", secret)
}
if addr == "" {
log.Fatalf("[fatal] invalid addr: %+q", addr)
}
}
func main() {
hook, _ := github.New(github.Options.Secret(secret))
http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
payload, err := hook.Parse(r, github.PushEvent, github.PullRequestEvent)
if err != nil {
log.Printf("[receiving] hook.Parse: err=%v\n", err)
w.WriteHeader(http.StatusBadRequest)
return
}
switch p := payload.(type) {
case github.PushPayload:
// fmt.Printf("[receiving] push: %+v\n", push) // ** verbose
fmt.Printf("[receiving] push: repo=%s, sender=%s\n", p.Repository.FullName, p.Sender.Login)
prjKey := strings.ReplaceAll(p.Repository.FullName, "/", "_")
prjKey = strings.ReplaceAll(prjKey, "-", "_")
envKey := fmt.Sprintf("PRJ_PATH_%s", prjKey)
prjPath := os.Getenv(envKey)
if err := pull(prjPath); err != nil {
log.Printf("[error] pull: path=%q, err=%v\n", prjPath, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
fmt.Printf("[done] pull: path=%q\n", prjPath)
case github.PullRequestPayload:
// Do whatever you want from here...
fmt.Printf("[receiving] pullRequest: repo=%s, sender=%s\n", p.Repository.FullName, p.Sender.Login)
}
})
http.ListenAndServe(addr, nil)
}