-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreceiver.go
138 lines (111 loc) · 2.11 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package sse
import (
"bytes"
"context"
"errors"
"io"
)
type receiver struct {
ch <-chan *Message
close func() error
}
var _ Receiver = &receiver{}
var _ io.Closer = &receiver{}
func (r *receiver) Receive(ctx context.Context) (*Message, error) {
select {
case <-ctx.Done():
return nil, ctx.Err()
case msg, ok := <-r.ch:
if !ok {
return nil, io.EOF
}
return msg, nil
}
}
func (r *receiver) Close() error {
return r.close()
}
func NewReceiver(rc io.ReadCloser) Receiver {
return &receiver{
ch: Parse(rc),
close: rc.Close,
}
}
func Parse(r io.Reader) <-chan *Message {
ch := make(chan *Message)
var buffer bytes.Buffer
go func() {
defer close(ch)
for {
msg, err := parseMessage(r, &buffer)
done := errors.Is(err, io.EOF)
if err != nil && !done {
return
}
ch <- msg
if done || msg.Event == "done" {
return
}
}
}()
return ch
}
func parseMessage(r io.Reader, buffer *bytes.Buffer) (*Message, error) {
msg := &Message{}
lastMsgWasComment := false
for {
buffer.Reset()
err := readLine(r, buffer)
if err != nil {
return msg, err
}
line := buffer.Bytes()
if len(line) == 0 {
if lastMsgWasComment {
lastMsgWasComment = false
continue
}
break
}
// it means that the line is a comment
// and we can ignore it
if line[0] == ':' {
lastMsgWasComment = true
continue
}
index := bytes.Index(line, []byte(": "))
if index == -1 {
// this shouldn't happen, but if it does
// it means that the line is invalid
// and we can ignore it
continue
}
field := string(line[:index])
value := string(line[index+2:])
switch field {
case "id":
msg.Id = &value
case "event":
msg.Event = value
case "data":
msg.Data = &value
}
}
return msg, nil
}
// fill the buffer with the content of the line
// until a newline character is found, it will eat the newline
// but it will not be part of the buffer
func readLine(r io.Reader, buffer *bytes.Buffer) error {
b := make([]byte, 1)
for {
_, err := r.Read(b)
if err != nil {
return err
}
if b[0] == '\n' {
return nil
}
buffer.Write(b)
}
}