This repository has been archived by the owner on Sep 2, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwebhooks.go
96 lines (76 loc) · 2.13 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package factorial
import (
"bytes"
"encoding/json"
"net/http"
)
const (
webhookURL = "/api/v1/webhooks"
)
// Webhook contains all the webhook information
type Webhook struct {
SubscriptionType string `json:"subscription_type"`
}
// CreateWebhookRequest keeps the information needed
// for create a new webhook
type CreateWebhookRequest struct {
SubscriptionType string `json:"subscription_type"`
TargetURL string `json:"target_url"`
}
// DeleteWebhookRequest keeps the information needed
// for delete a new webhook
type DeleteWebhookRequest struct {
SubscriptionType string `json:"subscription_type"`
}
// CreateWebhook creates a subscription for a determined webhook type.
// If webhook already exists, it just changes the target_url.
func (c Client) CreateWebhook(w CreateWebhookRequest) (Webhook, error) {
var webhook Webhook
bytes, err := json.Marshal(w)
if err != nil {
return webhook, err
}
resp, err := c.post(webhookURL, bytes)
if err != nil {
return webhook, err
}
if err := json.NewDecoder(resp.Body).Decode(&webhook); err != nil {
return webhook, err
}
return webhook, nil
}
// DeleteWebhook deletes a subscription to a webhook.
func (c Client) DeleteWebhook(w DeleteWebhookRequest) (Webhook, error) {
var webhook Webhook
body, err := json.Marshal(w)
if err != nil {
return webhook, err
}
// Not used the Client because this endpoint is not following the REST definition
// and we don't want to break our pattern for it
req, err := http.NewRequest(http.MethodDelete, c.apiURL+webhookURL, bytes.NewReader(body))
if err != nil {
return webhook, err
}
resp, err := c.Do(req)
if err != nil {
return webhook, err
}
if err := json.NewDecoder(resp.Body).Decode(&webhook); err != nil {
return webhook, err
}
return webhook, nil
}
// ListWebhooks gets a list of all subscribed webhooks for current user.
func (c Client) ListWebhooks() ([]Webhook, error) {
var webhooks []Webhook
resp, err := c.get(webhookURL, nil)
if err != nil {
return webhooks, err
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(&webhooks); err != nil {
return webhooks, err
}
return webhooks, nil
}