-
-
Notifications
You must be signed in to change notification settings - Fork 201
/
web_hook.go
111 lines (103 loc) · 2.26 KB
/
web_hook.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package webhook
import (
"errors"
"fmt"
"strings"
"github.com/admpub/nging/v5/application/library/restclient"
)
var Methods = [6]string{`GET`, `POST`, `PUT`, `HEAD`, `PATCH`, `DELETE`}
var (
ErrInvalidHTTPMethod = errors.New(`invalid http method`)
ErrWebhookUrlRequired = errors.New(`webhook URL cannot be empty`)
ErrBadHTTPStatus = errors.New("bad HTTP status")
)
func New() *Webhook {
return &Webhook{}
}
type Webhook struct {
Name string
Method string
Url string
Content string
Header string
headers []string
}
// AddHeader(`headerName=headerValue`)
func (w *Webhook) AddHeader(kvs ...string) *Webhook {
w.headers = append(w.headers, kvs...)
return w
}
func (w *Webhook) Validate() error {
if len(w.Url) == 0 {
return ErrWebhookUrlRequired
}
for _, method := range Methods {
if method == w.Method {
return nil
}
}
return ErrInvalidHTTPMethod
}
func (w *Webhook) Exec(contentTagReplacer func(string) string, urlTagReplacer func(string) string) error {
client := restclient.RestyRetryable()
if len(w.Content) > 0 {
content := w.Content
if contentTagReplacer != nil {
content = contentTagReplacer(content)
}
client.SetBody(content)
}
header := strings.TrimSpace(w.Header)
if len(header) > 0 {
for _, h := range strings.Split(header, "\n") {
h = strings.TrimSpace(h)
if len(h) == 0 {
continue
}
parts := strings.SplitN(h, `=`, 2)
if len(parts) != 2 {
continue
}
for k, v := range parts {
parts[k] = strings.TrimSpace(v)
}
client.SetHeader(parts[0], parts[1])
}
}
if len(w.headers) > 0 {
for _, h := range w.headers {
parts := strings.SplitN(h, `=`, 2)
if len(parts) != 2 {
continue
}
for k, v := range parts {
parts[k] = strings.TrimSpace(v)
}
client.SetHeader(parts[0], parts[1])
}
}
name := w.Name
if len(name) == 0 {
name = w.Url
}
url := w.Url
if urlTagReplacer != nil {
url = urlTagReplacer(url)
}
method := w.Method
if len(method) == 0 {
if len(w.Content) > 0 {
method = `POST`
} else {
method = `GET`
}
}
resp, err := client.Execute(method, url)
if err != nil {
return fmt.Errorf(`%s: %w`, name, err)
}
if resp.IsError() {
return fmt.Errorf(`%s: %w: %d: %s`, name, ErrBadHTTPStatus, resp.StatusCode(), resp.String())
}
return err
}