forked from orus-io/nats-websocket-gw
-
Notifications
You must be signed in to change notification settings - Fork 1
/
commands-reader.go
56 lines (51 loc) · 1.13 KB
/
commands-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
package gw
import (
"bufio"
"bytes"
"fmt"
"io"
"strconv"
)
type CommandsReader struct {
io.Reader
br *bufio.Reader
}
func NewCommandsReader(src io.Reader) CommandsReader {
return CommandsReader{
Reader: src,
br: bufio.NewReader(src),
}
}
func (cr CommandsReader) nextCommand() ([]byte, error) {
var msg []byte
line, err := cr.br.ReadBytes('\n')
if err != nil {
return nil, err
}
if bytes.Equal(line[0:3], []byte("MSG")) {
msg = line[:]
splitted := bytes.Split(line, []byte(" "))
sizeStr := splitted[len(splitted)-1]
sizeStr = sizeStr[:len(sizeStr)-2]
size, err := strconv.Atoi(string(sizeStr))
if err != nil {
return nil, fmt.Errorf("Error reading MSG size: %s", err)
}
// the '-2' is to account for the trailing \r\n which is after the payload
for size > -2 {
chunk, err := cr.br.ReadBytes('\n')
if err != nil {
return nil, fmt.Errorf("Error reading MSG payload: %s", err)
}
size -= len(chunk)
msg = append(msg, chunk...)
}
if size != -2 {
return nil, fmt.Errorf(
"Error reading MSG payload. Got %d extra bytes", -size-2)
}
} else {
msg = line
}
return msg, nil
}