This repository has been archived by the owner on Nov 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
receiver.go
88 lines (71 loc) · 1.64 KB
/
receiver.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
package main
import (
"bufio"
"log"
"net"
"os"
"regexp"
"github.com/ActiveState/tail"
)
var (
ValidJSON = regexp.MustCompile("\\{.*\\}")
)
type Receiver struct {
Host string // listen address
Port int // listen port
messages chan []byte // incomming messages
}
// create a new receiver server
func NewReceiver(host string, port, bufferSize int) Receiver {
return Receiver{
Host: host,
Port: port,
messages: make(chan []byte, bufferSize),
}
}
func (r *Receiver) ListenAndServe() error {
addr := net.UDPAddr{Port: r.Port, IP: net.ParseIP(r.Host)}
conn, err := net.ListenUDP("udp", &addr)
if err != nil {
return err
}
defer conn.Close()
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
b := scanner.Bytes()
if !ValidJSON.Match(b) {
log.Printf("Receiver: Error: Invalid Message\n")
continue
}
r.messages <- b
}
if err = scanner.Err(); err != nil {
return err
}
return nil
}
// tail a file on disk
func (r *Receiver) TailFile(path string) (*tail.Tail, error) {
t, err := tail.TailFile(path, tail.Config{Follow: true, ReOpen: true})
return t, err
}
// listen for tail events as if they were entries on the network socket
func (r *Receiver) ListenToTail(t *tail.Tail) {
for line := range t.Lines {
m := Entry{Message: line.Text}
r.messages <- m.ToJSON()
}
}
// write entries on messages channel to filename
func (r *Receiver) WriteToFile(filename string) {
file, err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_TRUNC|os.O_APPEND, 0644)
if err != nil {
log.Printf("Writer: Error: %s\n", err)
return
}
defer file.Close()
for {
file.Write(<-r.messages)
file.Write([]byte("\n"))
}
}