-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathstream.go
62 lines (58 loc) · 1.34 KB
/
stream.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
package rfc5424
import (
"fmt"
"io"
"io/ioutil"
"strconv"
)
// WriteTo writes the message to a stream of messages in the style defined
// by RFC-5425. (It does not implement the TLS stuff described in the RFC, just
// the length delimiting.
func (m Message) WriteTo(w io.Writer) (int64, error) {
b, err := m.MarshalBinary()
if err != nil {
return 0, err
}
n, err := fmt.Fprintf(w, "%d %s", len(b), b)
return int64(n), err
}
func readUntilSpace(r io.Reader) ([]byte, int, error) {
buf := []byte{}
nbytes := 0
for {
b := []byte{0}
n, err := r.Read(b)
nbytes += n
if err != nil {
return nil, nbytes, err
}
if b[0] == ' ' {
return buf, nbytes, nil
}
buf = append(buf, b...)
}
}
// ReadFrom reads a single record from an RFC-5425 style stream of messages
func (m *Message) ReadFrom(r io.Reader) (int64, error) {
lengthBuf, n1, err := readUntilSpace(r)
if err != nil {
return 0, err
}
length, err := strconv.Atoi(string(lengthBuf))
if err != nil {
return 0, err
}
r2 := io.LimitReader(r, int64(length))
buf, err := ioutil.ReadAll(r2)
if err != nil {
return int64(n1 + len(buf)), err
}
if len(buf) != int(length) {
return int64(n1 + len(buf)), fmt.Errorf("Expected to read %d bytes, got %d", length, len(buf))
}
err = m.UnmarshalBinary(buf)
if err != nil {
return 0, err
}
return int64(n1 + len(buf)), err
}