-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotify.go
72 lines (67 loc) · 1.72 KB
/
notify.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
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"github.com/bitly/nsq/nsq"
"log"
"net/http"
"strings"
"time"
)
type AdminAction struct {
Action string `json:"action"`
Topic string `json:"topic"`
Channel string `json:"channel,omitempty"`
Node string `json:"node,omitempty"`
Timestamp int64 `json:"timestamp"`
User string `json:"user,omitempty"`
RemoteIP string `json:"remote_ip"`
UserAgent string `json:"user_agent"`
}
func HandleAdminActions() {
for action := range notifications {
content, err := json.Marshal(action)
if err != nil {
log.Printf("Error serializing admin action! %s", err)
}
httpclient := &http.Client{Transport: nsq.NewDeadlineTransport(10 * time.Second)}
log.Printf("Posting notification to %s", *notificationHTTPEndpoint)
_, err = httpclient.Post(*notificationHTTPEndpoint, "application/json", bytes.NewBuffer(content))
if err != nil {
log.Printf("Error posting notification: %s", err)
}
}
}
func basicAuthUser(req *http.Request) string {
s := strings.SplitN(req.Header.Get("Authorization"), " ", 2)
if len(s) != 2 || s[0] != "Basic" {
return ""
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return ""
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return ""
}
return pair[0]
}
func NotifyAdminAction(actionType string, topicName string, channelName string, node string, req *http.Request) {
if *notificationHTTPEndpoint == "" {
return
}
action := &AdminAction{
actionType,
topicName,
channelName,
node,
time.Now().Unix(),
basicAuthUser(req),
req.RemoteAddr,
req.UserAgent(),
}
// Perform all work in a new goroutine so this never blocks
go func() { notifications <- action }()
}