-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook.go
84 lines (80 loc) · 1.7 KB
/
webhook.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
package main
import (
"log"
"net"
"net/http"
"time"
)
var retry time.Duration = 10 * time.Second
func getHandler(ch chan struct{}, ts string, allowFrom []*net.IPNet) (func(w http.ResponseWriter, r *http.Request), error) {
timeout, err := time.ParseDuration(ts)
if err != nil {
return nil, err
}
var access time.Time
return func(w http.ResponseWriter, r *http.Request) {
ip, err := parseIP(r.RemoteAddr)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte{})
return
}
allowFlag := false
for _, allow := range allowFrom {
if allow.Contains(ip) {
allowFlag = true
break
}
}
if !allowFlag {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte{})
return
}
log.Println("webhook received")
access = time.Now()
w.Write([]byte{})
go func() {
t := time.NewTimer(timeout)
<-t.C
if access.Add(timeout).Before(time.Now()) {
log.Println("webhook timeout")
ch <- struct{}{}
}
}()
}, nil
}
func startListen(wc *webhookConfig) (chan struct{}, error) {
ch := make(chan struct{})
mux := http.NewServeMux()
if wc.Timeout == "" {
wc.Timeout = "30s"
}
networks := []*net.IPNet{}
for _, allowStr := range wc.AllowFrom {
_, subnet, err := net.ParseCIDR(allowStr)
if err != nil {
log.Println(err)
}
networks = append(networks, subnet)
}
handler, err := getHandler(ch, wc.Timeout, networks)
if err != nil {
return nil, err
}
mux.Handle("/", http.HandlerFunc(handler))
srv := &http.Server{
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
Addr: wc.Listen,
Handler: mux,
}
go func() {
for {
err := srv.ListenAndServe()
log.Println(err)
time.Sleep(retry)
}
}()
return ch, nil
}