forked from googollee/go-socket.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message_reader.go
60 lines (55 loc) · 957 Bytes
/
message_reader.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
package socketio
import (
"bufio"
)
type messageReader struct {
reader *bufio.Reader
message string
firstRead bool
}
func newMessageReader(bufr *bufio.Reader) (*messageReader, error) {
if _, err := bufr.ReadBytes('"'); err != nil {
return nil, err
}
msg, err := bufr.ReadBytes('"')
if err != nil {
return nil, err
}
for {
b, err := bufr.Peek(1)
if err != nil {
return nil, err
}
if b[0] == ',' {
bufr.ReadByte()
break
}
if b[0] != ' ' {
break
}
bufr.ReadByte()
}
return &messageReader{
reader: bufr,
message: string(msg[:len(msg)-1]),
firstRead: true,
}, nil
}
func (r *messageReader) Message() string {
return r.message
}
func (r *messageReader) Read(b []byte) (int, error) {
if len(b) == 0 {
return 0, nil
}
if r.firstRead {
r.firstRead = false
b[0] = '['
n, err := r.reader.Read(b[1:])
if err != nil {
return -1, err
}
return n + 1, err
}
return r.reader.Read(b)
}