/
main.go
72 lines (55 loc) · 1.23 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
package main
import (
"encoding/json"
"fmt"
"github.com/google/go-github/github"
"github.com/rjz/githubhook"
"log"
"net/http"
)
const OK_RESPONSE = ":^)"
type WebhookServer struct {
secret string
}
func String(s string) *string {
str := new(string)
*str = s
return str
}
func Int(i int) *int {
j := new(int)
*j = i
return j
}
func parsePullRequestEvent(hook *githubhook.Hook) *github.PullRequestEvent {
evt := github.PullRequestEvent{}
json.Unmarshal(hook.Payload, &evt)
return &evt
}
func (s *WebhookServer) handle(w http.ResponseWriter, r *http.Request) {
body, err := githubhook.Parse([]byte(s.secret), r)
if err != nil {
log.Println("Webhook parsing failed", err)
http.Error(w, err.Error(), 400)
return
}
go func() {
switch body.Event {
case "pull_request":
go HandlePullRequestEvent(parsePullRequestEvent(body))
default:
log.Printf("Saw unknown event '%s' and waved as it went by.", body.Event)
}
}()
w.Write([]byte(OK_RESPONSE))
}
func main() {
c := NewConfig()
server := WebhookServer{
secret: c.githubWebhookSecret,
}
serverPort := fmt.Sprintf(":%d", c.port)
log.Printf("Listening on %s", serverPort)
http.HandleFunc("/hooks/github", server.handle)
http.ListenAndServe(serverPort, nil)
}