@@ -2,31 +2,51 @@ package eventsource
2
2
3
3
import (
4
4
"bytes"
5
- "io"
6
5
"io/ioutil"
7
6
"strconv"
7
+ "strings"
8
8
)
9
9
10
10
// Holds the data for an event
11
11
type Event struct {
12
- id [] byte
13
- data [][] byte
14
- event [] byte
12
+ id string
13
+ data []string
14
+ event string
15
15
retry uint64
16
16
buf bytes.Buffer
17
17
bufSet bool
18
18
}
19
19
20
- // DataEvent creates a new Event with the data field set
21
- func DataEvent (data string ) * Event {
22
- e := & Event {}
23
- io .WriteString (e , data )
20
+ // ID sets the event ID
21
+ func (e * Event ) ID (id string ) * Event {
22
+ e .id = id
24
23
return e
25
24
}
26
25
27
- // ID sets the event ID
28
- func (e * Event ) ID (id string ) {
29
- e .id = []byte (id )
26
+ // Type sets the event's event: field
27
+ func (e * Event ) Type (t string ) * Event {
28
+ e .event = t
29
+ return e
30
+ }
31
+
32
+ // Type sets the event's retry: field
33
+ func (e * Event ) Retry (t uint64 ) * Event {
34
+ e .retry = t
35
+ return e
36
+ }
37
+
38
+ // Data replaces the data with the given string
39
+ func (e * Event ) Data (dat string ) * Event {
40
+ // truncate
41
+ e .data = e .data [:0 ]
42
+ e .WriteString (dat )
43
+ return e
44
+ }
45
+
46
+ // Adds data to the event without overwriting
47
+ func (e * Event ) AppendData (dat string ) * Event {
48
+ e .WriteString (dat )
49
+ return e
30
50
}
31
51
32
52
// Read the event in wire format
@@ -41,22 +61,22 @@ func (e *Event) Read(p []byte) (int, error) {
41
61
// event:
42
62
if len (e .event ) > 0 {
43
63
e .buf .WriteString ("event: " )
44
- e .buf .Write (e .event )
64
+ e .buf .WriteString (e .event )
45
65
e .buf .WriteByte ('\n' )
46
66
}
47
67
48
68
// id:
49
69
if len (e .id ) > 0 {
50
70
e .buf .WriteString ("id: " )
51
- e .buf .Write (e .id )
71
+ e .buf .WriteString (e .id )
52
72
e .buf .WriteByte ('\n' )
53
73
}
54
74
55
75
// data:
56
76
if len (e .data ) > 0 {
57
77
for _ , entry := range e .data {
58
78
e .buf .WriteString ("data: " )
59
- e .buf .Write (entry )
79
+ e .buf .WriteString (entry )
60
80
e .buf .WriteByte ('\n' )
61
81
}
62
82
}
@@ -82,8 +102,13 @@ func (e *Event) Read(p []byte) (int, error) {
82
102
// Newlines will be split into multiple data entry lines, successive
83
103
// newlines are discarded
84
104
func (e * Event ) Write (p []byte ) (int , error ) {
105
+ e .WriteString (string (p ))
106
+ return len (p ), nil
107
+ }
108
+
109
+ func (e * Event ) WriteString (p string ) {
85
110
// split event on newlines
86
- split := bytes .Split (p , [] byte { '\n' } )
111
+ split := strings .Split (p , " \n " )
87
112
for _ , entry := range split {
88
113
// don't write empty entries
89
114
if len (entry ) == 0 {
@@ -92,7 +117,6 @@ func (e *Event) Write(p []byte) (int, error) {
92
117
e .data = append (e .data , entry )
93
118
}
94
119
e .bufSet = false
95
- return len (p ), nil
96
120
}
97
121
98
122
// WriteRaw sets an event directly in wire format
0 commit comments