/
pull.go
111 lines (91 loc) · 2.58 KB
/
pull.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
package pull
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/google/go-github/github"
)
type Middleware func(*github.Client, *github.PullRequest)
type Middlewares map[string][]Middleware
type Handler struct {
Client *github.Client
*Configuration
}
type Configuration struct {
Client *http.Client
Middlewares Middlewares
Secret string
}
func New(c Configuration) *Handler {
return &Handler{github.NewClient(c.Client), &c}
}
func (l *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
pingHandler(implementsHandler(secretHandler(l.Secret, mainHandler(l, runner)))).ServeHTTP(w, req)
}
func mainHandler(handler *Handler, run runnerFunc) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var event github.PullRequestEvent
err := decoder.Decode(&event)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Bad JSON")
return
}
fmt.Printf("%s %s:%d\n", *event.Action, *event.Repo.FullName, *event.Number)
w.WriteHeader(http.StatusAccepted)
//pending(l.Client, event.PullRequest)
go run(handler, event)
})
}
func pingHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
t := req.Header.Get("X-GitHub-Event")
if t == "ping" {
w.WriteHeader(http.StatusAccepted)
fmt.Fprintf(w, "Received ping")
return
}
next.ServeHTTP(w, req)
})
}
func implementsHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
t := req.Header.Get("X-GitHub-Event")
if t != "pull_request" {
w.WriteHeader(http.StatusNotImplemented)
fmt.Fprintf(w, "Unsupported event")
return
}
next.ServeHTTP(w, req)
})
}
func secretHandler(secret string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if secret != "" {
s := req.Header.Get("X-Hub-Signature")
if s == "" {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "X-Hub-Signature required for HMAC verification")
return
}
body, _ := ioutil.ReadAll(req.Body)
hash := hmac.New(sha1.New, []byte(secret))
hash.Write(body)
expected := "sha1=" + hex.EncodeToString(hash.Sum(nil))
if !hmac.Equal([]byte(expected), []byte(s)) {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "HMAC verification failed")
return
}
req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
}
next.ServeHTTP(w, req)
})
}