Skip to content

Commit d73832f

Browse files
committed
Event ReaderWriter interface
0 parents  commit d73832f

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

event.go

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package eventsource
2+
3+
import (
4+
"bytes"
5+
"strconv"
6+
)
7+
8+
// Holds the data for an event
9+
type Event struct {
10+
id []byte
11+
data [][]byte
12+
event []byte
13+
retry uint64
14+
buf bytes.Buffer
15+
bufSet bool
16+
}
17+
18+
// Read the event in wire format
19+
func (e *Event) Read(p []byte) (int, error) {
20+
if e.bufSet {
21+
return e.buf.Read(p)
22+
}
23+
24+
// Wipe out any existing data
25+
e.buf.Reset()
26+
27+
// event:
28+
if len(e.event) > 0 {
29+
e.buf.WriteString("event: ")
30+
e.buf.Write(e.event)
31+
e.buf.WriteByte('\n')
32+
}
33+
34+
// id:
35+
if len(e.id) > 0 {
36+
e.buf.WriteString("id: ")
37+
e.buf.Write(e.id)
38+
e.buf.WriteByte('\n')
39+
}
40+
41+
// data:
42+
if len(e.data) > 0 {
43+
for _, entry := range e.data {
44+
e.buf.WriteString("data: ")
45+
e.buf.Write(entry)
46+
e.buf.WriteByte('\n')
47+
}
48+
}
49+
50+
// retry:
51+
if e.retry > 0 {
52+
e.buf.WriteString("retry: ")
53+
e.buf.WriteString(strconv.FormatUint(e.retry, 10))
54+
e.buf.WriteByte('\n')
55+
}
56+
57+
e.buf.WriteByte('\n')
58+
e.bufSet = true
59+
60+
return e.buf.Read(p)
61+
}
62+
63+
// Write to the event. Buffer will be converted to one or more
64+
// `data` sections in wire format
65+
//
66+
// Successive calls to write will each create data entry lines
67+
//
68+
// Newlines will be split into multiple data entry lines, successive
69+
// newlines are discarded
70+
func (e *Event) Write(p []byte) (int, error) {
71+
// split event on newlines
72+
split := bytes.Split(p, []byte{'\n'})
73+
for _, entry := range split {
74+
// don't write empty entries
75+
if len(entry) == 0 {
76+
continue
77+
}
78+
e.data = append(e.data, entry)
79+
}
80+
e.bufSet = false
81+
return len(p), nil
82+
}

0 commit comments

Comments
 (0)