/
slack_client.go
87 lines (71 loc) · 2.07 KB
/
slack_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
84
85
86
87
package adapters
/*
import (
"encoding/json"
"net/http"
"regexp"
"strings"
"github.com/grokify/commonchat/slack"
"github.com/grokify/gotilla/net/httputilmore"
log "github.com/sirupsen/logrus"
"github.com/valyala/fasthttp"
)
const (
HTTPMethod = "POST"
)
var (
WebhookBaseURL = "https://hooks.slack.com/services/"
)
type ClientType int
const (
HTTP ClientType = iota
FastHTTP
)
type SlackWebhookClient struct {
HttpClient *http.Client
FastClient fasthttp.Client
WebhookUrl string
UrlPrefix *regexp.Regexp
}
func NewSlackWebhookClient(urlOrUid string, clientType ClientType) (SlackWebhookClient, error) {
log.WithFields(log.Fields{
"lib": "slack_client.go",
"request_url_client_init": urlOrUid}).Debug("")
client := SlackWebhookClient{UrlPrefix: regexp.MustCompile(`^https:`)}
client.WebhookUrl = client.BuildWebhookURL(urlOrUid)
if clientType == FastHTTP {
client.FastClient = fasthttp.Client{}
} else {
client.HttpClient = httputilmore.NewHttpClient()
}
return client, nil
}
func (client *SlackWebhookClient) BuildWebhookURL(urlOrUid string) string {
rx := regexp.MustCompile(`^https:`)
rs := rx.FindString(urlOrUid)
if len(rs) > 0 {
log.WithFields(log.Fields{
"lib": "slack_client.go",
"request_url_http_match": urlOrUid}).Debug("")
return urlOrUid
}
return strings.Join([]string{WebhookBaseURL, urlOrUid}, "")
}
func (client *SlackWebhookClient) PostWebhookFast(url string, message slack.Message) (*fasthttp.Request, *fasthttp.Response, error) {
req := fasthttp.AcquireRequest()
resp := fasthttp.AcquireResponse()
bytes, err := json.Marshal(message)
if err != nil {
return req, resp, err
}
req.SetBody(bytes)
req.Header.SetMethod(HTTPMethod)
req.Header.SetRequestURI(url)
req.Header.Set(httputilmore.ContentTypeHeader, httputilmore.ContentTypeValueJSONUTF8)
err = client.FastClient.Do(req, resp)
return req, resp, err
}
func (client *SlackWebhookClient) PostWebhookGUIDFast(urlOrUid string, message slack.Message) (*fasthttp.Request, *fasthttp.Response, error) {
return client.PostWebhookFast(client.BuildWebhookURL(urlOrUid), message)
}
*/