/
rest.go
61 lines (51 loc) · 1.28 KB
/
rest.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
package notifiers
import (
"bytes"
"encoding/json"
"fmt"
"github.com/go-logr/logr"
"net"
"net/http"
"net/url"
"time"
)
// REST Endpoint Notifier
type EndpointNotifier struct {
endpoint string
}
func NewEndpointNotifier(log logr.Logger, endpoint string) (*EndpointNotifier, error) {
log.Info("Enabling REST endpoint notifier", "endpoint", endpoint)
uri, err := url.ParseRequestURI(endpoint)
if err != nil || uri.Host == "" {
// POST requires a valid endpoint scheme, add a safe default if none is provided
uri, err = url.ParseRequestURI("http://" + endpoint)
if err != nil {
return nil, err
}
}
// Validate endpoint connectivity
conn, err := net.DialTimeout("tcp", uri.Host, 5*time.Second)
if err != nil {
return nil, err
} else {
conn.Close()
}
return &EndpointNotifier{
endpoint: uri.String(),
}, nil
}
func (e EndpointNotifier) Notify(log logr.Logger, notification LabelUpdateNotification) error {
payload, err := json.Marshal(notification)
if err != nil {
log.Error(err, "failed to marshal JSON payload")
return err
}
msg := fmt.Sprintf("notifying %s", e.endpoint)
log.Info(msg)
_, err = http.Post(e.endpoint, "application/json", bytes.NewBuffer(payload))
if err != nil {
log.Error(err, "failed to POST to endpoint")
return err
}
return nil
}