Skip to content

Commit 442363a

Browse files
committed
feat: use bufio scanner to decode events
1 parent 9246475 commit 442363a

File tree

1 file changed

+6
-8
lines changed

1 file changed

+6
-8
lines changed

sse-decoder.go

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package sse
66

77
import (
8+
"bufio"
89
"bytes"
910
"io"
1011
)
@@ -37,19 +38,16 @@ func (d *decoder) dispatchEvent(event Event, data string) {
3738
}
3839

3940
func (d *decoder) decode(r io.Reader) ([]Event, error) {
40-
buf, err := io.ReadAll(r)
41-
if err != nil {
42-
return nil, err
43-
}
44-
4541
var currentEvent Event
4642
dataBuffer := new(bytes.Buffer)
4743
// TODO (and unit tests)
4844
// Lines must be separated by either a U+000D CARRIAGE RETURN U+000A LINE FEED (CRLF) character pair,
4945
// a single U+000A LINE FEED (LF) character,
5046
// or a single U+000D CARRIAGE RETURN (CR) character.
51-
lines := bytes.Split(buf, []byte{'\n'})
52-
for _, line := range lines {
47+
s := bufio.NewScanner(r)
48+
for s.Scan() {
49+
line := s.Bytes()
50+
5351
if len(line) == 0 {
5452
// If the line is empty (a blank line). Dispatch the event.
5553
d.dispatchEvent(currentEvent, dataBuffer.String())
@@ -113,5 +111,5 @@ func (d *decoder) decode(r io.Reader) ([]Event, error) {
113111
// Once the end of the file is reached, the user agent must dispatch the event one final time.
114112
d.dispatchEvent(currentEvent, dataBuffer.String())
115113

116-
return d.events, nil
114+
return d.events, s.Err()
117115
}

0 commit comments

Comments
 (0)