-
Notifications
You must be signed in to change notification settings - Fork 0
/
githubservicehook.go
62 lines (49 loc) · 1.07 KB
/
githubservicehook.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
package githubservicehook
import (
"net/http"
"sync"
)
type payloadProcessor func(Payload)
type hookProcess struct {
processMutex sync.Mutex
processor payloadProcessor
server *http.Server
}
func (this *hookProcess) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.WriteHeader(http.StatusBadRequest)
return
}
err := r.ParseForm()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
body := r.FormValue("payload")
payload, err := parsePayload(body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
go this.processNextPayload(payload)
}
func (this *hookProcess) processNextPayload(payload Payload) {
this.processMutex.Lock()
defer this.processMutex.Unlock()
// do the thing
this.processor(payload)
}
// this will block
func (this *hookProcess) Start(addr string) error {
this.server = &http.Server{
Addr: addr,
Handler: this,
}
return this.server.ListenAndServe()
}
func New(f payloadProcessor) *hookProcess {
return &hookProcess{
processMutex: sync.Mutex{},
processor: f,
}
}