-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathwebhook_client.go
83 lines (66 loc) · 1.82 KB
/
webhook_client.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
package bearychat
import (
"encoding/json"
"errors"
"io"
"net/http"
)
// WebhookResponse represents a response.
type WebhookResponse struct {
StatusCode int `json:"-"`
Code int `json:"code"`
Error string `json:"error,omitempty"`
Result *json.RawMessage `json:"result"`
}
func (w WebhookResponse) IsOk() bool {
return w.Code == 0
}
// WebhookClient represents any webhook client can send message to BearyChat.
type WebhookClient interface {
// Set webhook webhook.
SetWebhook(webhook string) WebhookClient
// Set http client.
SetHTTPClient(client *http.Client) WebhookClient
// Send webhook payload.
Send(payload io.Reader) (*WebhookResponse, error)
}
type webhookClient struct {
httpClient *http.Client
Webhook string
}
// Creates a new incoming webhook client.
//
// For full documentation, visit https://bearychat.com/integrations/incoming .
func NewIncomingWebhookClient(webhook string) *webhookClient {
return &webhookClient{
httpClient: http.DefaultClient,
Webhook: webhook,
}
}
func (w *webhookClient) SetWebhook(webhook string) WebhookClient {
w.Webhook = webhook
return w
}
func (w *webhookClient) SetHTTPClient(c *http.Client) WebhookClient {
w.httpClient = c
return w
}
func (w *webhookClient) Send(payload io.Reader) (*WebhookResponse, error) {
if w.Webhook == "" {
return nil, errors.New("webhook url is required")
}
if w.httpClient == nil {
return nil, errors.New("http client is required")
}
resp, err := w.httpClient.Post(w.Webhook, "application/json", payload)
if err != nil {
return nil, err
}
defer resp.Body.Close()
webhookResponse := new(WebhookResponse)
webhookResponse.StatusCode = resp.StatusCode
if err := json.NewDecoder(resp.Body).Decode(webhookResponse); err != nil {
return nil, err
}
return webhookResponse, nil
}