1
1
package webhooks
2
2
3
3
import (
4
+ "context"
4
5
"encoding/json"
5
6
"fmt"
6
7
"io/ioutil"
@@ -21,7 +22,7 @@ type Configuration struct {
21
22
22
23
type actionConfiguration struct {
23
24
secretKey string
24
- handle Handler
25
+ handle HandlerContext
25
26
}
26
27
27
28
// The Handler type is used to define webhook processors.
@@ -30,6 +31,12 @@ type actionConfiguration struct {
30
31
// pass a webhook body with a payload field decoded (ie. one of webhooks structures).
31
32
type Handler func (* Webhook ) error
32
33
34
+ // The HandlerContext type is used to define webhook processors.
35
+ //
36
+ // It can be used with WebhookHandler, in which case WebhookHandler will
37
+ // pass a webhook body with a payload field decoded (ie. one of webhooks structures).
38
+ type HandlerContext func (context.Context , * Webhook ) error
39
+
33
40
// NewConfiguration creates basic WebhookHandler configuration that
34
41
// processes no webhooks and uses http.Error to handle webhook processing
35
42
// errors.
@@ -46,6 +53,19 @@ func NewConfiguration() *Configuration {
46
53
// Otherwise, webhook's secret is strictly validated. In case of any mismatch between expected and actual secret key,
47
54
// webhook processing is stopped and error is returned.
48
55
func (cfg * Configuration ) WithAction (action string , handler Handler , secretKey string ) * Configuration {
56
+ cfg .actions [action ] = & actionConfiguration {
57
+ handle : func (ctx context.Context , wh * Webhook ) error { return handler (wh ) },
58
+ secretKey : secretKey ,
59
+ }
60
+ return cfg
61
+ }
62
+
63
+ // WithActionContext allows to attach custom webhook HandlerContext for given webhook action.
64
+ //
65
+ // If secretKey is an empty string, then no validation of webhook's secret is performed.
66
+ // Otherwise, webhook's secret is strictly validated. In case of any mismatch between expected and actual secret key,
67
+ // webhook processing is stopped and error is returned.
68
+ func (cfg * Configuration ) WithActionContext (action string , handler HandlerContext , secretKey string ) * Configuration {
49
69
cfg .actions [action ] = & actionConfiguration {
50
70
handle : handler ,
51
71
secretKey : secretKey ,
@@ -145,7 +165,7 @@ func NewWebhookHandler(cfg *Configuration) http.HandlerFunc {
145
165
}
146
166
wh .Payload = payload
147
167
148
- if err = acfg .handle (& wh ); err != nil {
168
+ if err = acfg .handle (r . Context (), & wh ); err != nil {
149
169
cfg .handleError (w , fmt .Sprintf ("webhook handler error: %v" , err ), http .StatusInternalServerError )
150
170
return
151
171
}
0 commit comments