-
Notifications
You must be signed in to change notification settings - Fork 91
/
handlers.go
68 lines (61 loc) · 1.63 KB
/
handlers.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
package main
import (
"fmt"
"net/http"
"github.com/techjacker/diffence"
)
const (
msgHealthOk = "ok"
msgBadRequest = "bad request"
msgIgnore = "Not a push evt; ignoring"
msgNoViolationsFound = "Push contains no offenses"
msgViolationFound = "Push contains violations"
)
// GithubHandler is a github integration HTTP handler
func GithubHandler(dc diffence.Checker, dg DiffGetterHTTP, log Log) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// decode github push event payload
gitRes := &GithubResponse{}
err := DecodeJSON(r.Body, gitRes)
if err != nil {
http.Error(w, msgBadRequest, http.StatusBadRequest)
return
}
// analyse all pushed commits
results := diffence.Results{}
for _, commit := range gitRes.Commits {
resp, err := dg.Get(gitRes.getDiffURL(commit.ID))
if err != nil {
http.Error(w, msgBadRequest, http.StatusBadRequest)
return
}
diffRes, err := dc.Check(resp.Body)
resp.Body.Close()
if err != nil {
http.Error(w, msgBadRequest, http.StatusBadRequest)
return
}
results = append(results, diffRes)
}
if results.Matches() < 1 {
fmt.Fprintf(w, "%s\n", msgNoViolationsFound)
return
}
for _, res := range results {
if res.Matches() > 0 {
log.Log(
res.MatchedRules,
gitRes.Repository.Owner.Name,
gitRes.Repository.Name,
gitRes.Compare,
)
}
}
fmt.Fprintf(w, "%s\n", msgViolationFound)
})
}
// HealthHandler is an endpoint for healthchecks
func HealthHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(msgHealthOk))
}