-
Notifications
You must be signed in to change notification settings - Fork 8
/
webhooks.go
76 lines (65 loc) · 1.8 KB
/
webhooks.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
package gocardless
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
)
// EventHandler is the interface that must be implemented to handle events from a webhook.
type EventHandler interface {
HandleEvent(Event) error
}
// EventHandlerFunc can be used to convert a function into an EventHandler
type EventHandlerFunc func(Event) error
// HandleEvent will call the EventHandlerFunc function
func (h EventHandlerFunc) HandleEvent(e Event) error {
return h(e)
}
// WebhookHandler allows you to process incoming events from webhooks.
type WebhookHandler struct {
EventHandler
secret string
}
// NewWebhookHandler instantiates a WebhookHandler which can be mounted as a net/http Handler.
func NewWebhookHandler(secret string, h EventHandler) (*WebhookHandler, error) {
if secret == "" {
return nil, errors.New("missing secret")
}
return &WebhookHandler{
EventHandler: h,
secret: secret,
}, nil
}
// ServeHTTP processes incoming webhooks and dispatches events to the corresponsing handlers.
func (h *WebhookHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sig, err := hex.DecodeString(r.Header.Get("Webhook-Signature"))
if len(sig) == 0 {
http.Error(w, "invalid signature", 498)
return
}
hash := hmac.New(sha256.New, []byte(h.secret))
body := io.TeeReader(r.Body, hash)
var events struct {
Events []Event `json:"events"`
}
err = json.NewDecoder(body).Decode(&events)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if !hmac.Equal(sig, hash.Sum(nil)) {
http.Error(w, "invalid signature", 498)
return
}
for _, event := range events.Events {
err := h.HandleEvent(event)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
w.WriteHeader(http.StatusNoContent)
}