-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnats.go
More file actions
89 lines (73 loc) · 1.49 KB
/
Copy pathnats.go
File metadata and controls
89 lines (73 loc) · 1.49 KB
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
package recorder
import (
"errors"
"fmt"
"net/url"
"strings"
"time"
"unicode"
"github.com/coredns/coredns/request"
"github.com/nats-io/nats.go"
)
// Errors.
var (
ErrInvalidTopic = errors.New("invalid subject / topic name")
ErrInvalidEndpoint = errors.New("invalid endpoint")
)
type natsOutput struct {
Topic string
Endpoint string
conn *nats.Conn
}
func (o *natsOutput) Record(r request.Request) error {
if err := o.Connect(); err != nil {
return err
}
now := time.Now()
message := fmt.Sprintf(
`{"ip":%q,"name":%q,"class":%q,"time":%q,"ts":%d}`,
r.IP(), r.Name(), r.Type(), now.Format(time.RFC3339), now.Unix())
return o.conn.Publish(o.Topic, []byte(message))
}
func (o *natsOutput) Connect() error {
if o.conn != nil {
if o.conn.IsConnected() {
return nil
}
}
nc, err := nats.Connect(o.Endpoint)
if err != nil {
return err
}
o.conn = nc
return nil
}
func (o *natsOutput) Flush() error {
if o.conn != nil {
if err := o.conn.Flush(); err != nil {
return err
}
o.conn.Close()
o.conn = nil
}
return nil
}
func (o *natsOutput) Validate() error {
if strings.Map(func(r rune) rune {
switch {
case unicode.IsLetter(r), unicode.IsDigit(r), r == '.':
return r
default:
return -1
}
}, o.Topic) != o.Topic {
return ErrInvalidTopic
}
endpoints := strings.Split(o.Endpoint, ",")
for _, endpoint := range endpoints {
if _, err := url.Parse(strings.TrimSpace(endpoint)); err != nil {
return ErrInvalidEndpoint
}
}
return nil
}