-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack.go
115 lines (89 loc) · 1.88 KB
/
slack.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
112
113
114
115
package slack
import (
"fmt"
"net/http"
"strings"
"sync"
)
// New function return configured go-slack engine.
// that already configured with default 5 seconds http timeout
func New(opt Option) *Engine {
var (
client *http.Client
)
client = &http.Client{
Timeout: 5 * defaultHTTPTimeOut,
}
return &Engine{
opt: opt,
client: client,
}
}
// Send function post given message to webhook urls
func (e *Engine) Send(message string) error {
if err := e.validateClient(); err != nil {
return err
}
for _, url := range e.opt.WebHookURLs {
err := e.send(http.MethodPost, url, message)
if err != nil {
return err
}
}
return nil
}
// SendAsync function will send to all registered webhooks asynchronously
// returning err chan for error info, channel will be closed when there's any error
// or all process is done
func (e *Engine) SendAsync(message string) chan error {
var (
errChan = make(chan error, 1)
err error
wg sync.WaitGroup
)
if err = e.validateClient(); err != nil {
errChan <- err
close(errChan)
return errChan
}
for _, url := range e.opt.WebHookURLs {
wg.Add(1)
go func(u string) {
defer wg.Done()
err := e.send(http.MethodPost, u, message)
if err != nil {
errChan <- err
}
}(url)
}
go func() {
wg.Wait()
close(errChan)
}()
return errChan
}
func (e *Engine) send(httpMethod, url string, message string) error {
var (
pl payload
)
pl.Text = e.opt.CustomMessage + message
resp, err := e.doString(httpMethod, url, pl)
if err != nil {
return err
}
// remove whitespace
resp = strings.ReplaceAll(resp, " ", "")
if resp != "ok" {
return fmt.Errorf("[go-slack] response is not ok : %s", resp)
}
return nil
}
func (e *Engine) validateClient() error {
if len(e.opt.WebHookURLs) < 1 {
return ErrNoWebhookRegistered
}
if e.client == nil {
return ErrEngineUsedWithoutNew
}
return nil
}