-
Notifications
You must be signed in to change notification settings - Fork 0
/
reporter.go
96 lines (81 loc) · 1.9 KB
/
reporter.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
package avchecker
import (
"bytes"
"fmt"
redis "github.com/xuyu/goredis"
"net/http"
"strings"
)
type Reporter interface {
SendStats([]byte) error
String() string
}
type redisQueueReporter struct {
queueName string
client *redis.Redis
}
func (r *redisQueueReporter) SendStats(stats []byte) error {
_, err := r.client.LPush(r.queueName, string(stats))
return err
}
func (r *redisQueueReporter) String() string {
return fmt.Sprintf("Redis 'LPUSH' to queue '%s'", r.queueName)
}
func urlWithDefaults(dialURL string) string {
if !strings.Contains(dialURL, "?") {
dialURL += "?"
}
if !strings.Contains(dialURL, "timeout=") {
if !strings.HasSuffix(dialURL, "?") {
dialURL += "&"
}
dialURL += "timeout=10s"
}
if !strings.Contains(dialURL, "maxidle=") {
if !strings.HasSuffix(dialURL, "?") && !strings.HasSuffix(dialURL, "&") {
dialURL += "&"
}
dialURL += "maxidle=1"
}
return dialURL
}
func NewRedisQueueReporter(queueName string, dialURL string) (Reporter, error) {
client, err := redis.DialURL(urlWithDefaults(dialURL))
if err != nil {
return nil, err
}
return &redisQueueReporter{
queueName: queueName,
client: client,
}, nil
}
type httpReporter struct {
url string
bodyType string
client *http.Client
}
func (h *httpReporter) SendStats(stats []byte) error {
_, err := h.client.Post(h.url, h.bodyType, bytes.NewReader(stats))
return err
}
func (r *httpReporter) String() string {
return fmt.Sprintf("http POST to %s", r.url)
}
func NewHttpReporter(url string, bodyType string) (Reporter, error) {
return &httpReporter{
client: http.DefaultClient,
bodyType: bodyType,
url: url,
}, nil
}
type stdoutReporter struct{}
func (r *stdoutReporter) SendStats(stats []byte) error {
fmt.Println(string(stats))
return nil
}
func (s *stdoutReporter) String() string {
return "print to stdout"
}
func NewStdoutReporter() Reporter {
return &stdoutReporter{}
}