-
Notifications
You must be signed in to change notification settings - Fork 8
/
http_notif.go
121 lines (97 loc) · 2.42 KB
/
http_notif.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
116
117
118
119
120
121
package main
import (
"bytes"
"fmt"
"io"
"net/http"
"text/template"
)
type encoding string
func (e encoding) AddHeader(header http.Header) {
header.Add("Content-Type", string(e))
}
func (e encoding) EscapeValue(value string) string {
switch e {
case EncodingForm:
return template.URLQueryEscaper(value)
case EncodingJson:
return template.JSEscapeString(value)
default:
return value
}
}
const (
EncodingForm encoding = "application/x-www-form-urlencoded"
EncodingJson encoding = "application/json"
)
type httpNotificator struct {
URL string
Method string
Encoding encoding
BodyTemplate string
}
var _ notificator = (*httpNotificator)(nil)
func NewHttpNotificator(cfg notificatorConfig) *httpNotificator {
return &httpNotificator{
URL: cfg.Params["Target"],
Method: cfg.Params["Method"],
Encoding: encoding(cfg.Params["Encoding"]),
BodyTemplate: cfg.Params["BodyTemplate"],
}
}
func (h *httpNotificator) Notify(amount uint64, comment string) error {
bodyData := &struct {
Amount uint64
Message string
}{
Amount: amount,
Message: h.Encoding.EscapeValue(comment),
}
urlTemplate, err := template.New("url").Parse(h.URL)
if err != nil {
return fmt.Errorf("error building URL template: %w", err)
}
bodyTemplate, err := template.New("body").Parse(h.BodyTemplate)
if err != nil {
return fmt.Errorf("error building body template: %w", err)
}
var buf bytes.Buffer
err = urlTemplate.Execute(&buf, bodyData)
if err != nil {
return fmt.Errorf("error executing URL template: %w", err)
}
url := buf.String()
buf.Reset()
err = bodyTemplate.Execute(&buf, bodyData)
if err != nil {
return fmt.Errorf("error executing body template: %w", err)
}
var bodyReader io.Reader
if h.Method == http.MethodPost {
bodyReader = &buf
}
req, err := http.NewRequest(h.Method, url, bodyReader)
if err != nil {
return fmt.Errorf("error creating request: %w", err)
}
h.Encoding.AddHeader(req.Header)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %w", err)
}
defer func() {
_ = resp.Body.Close()
}()
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("error reading response body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status code: %d (%s)",
resp.StatusCode, body)
}
return nil
}
func (h *httpNotificator) Target() string {
return h.URL
}