forked from nsqio/go-nsq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol.go
88 lines (75 loc) · 2.1 KB
/
protocol.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
package nsq
import (
"encoding/binary"
"errors"
"io"
"regexp"
"time"
)
var MagicV1 = []byte(" V1")
var MagicV2 = []byte(" V2")
const (
// when successful
FrameTypeResponse int32 = 0
// when an error occurred
FrameTypeError int32 = 1
// when it's a serialized message
FrameTypeMessage int32 = 2
)
// The amount of time nsqd will allow a client to idle, can be overriden
const DefaultClientTimeout = 60 * time.Second
var validTopicNameRegex = regexp.MustCompile(`^[\.a-zA-Z0-9_-]+$`)
var validChannelNameRegex = regexp.MustCompile(`^[\.a-zA-Z0-9_-]+(#ephemeral)?$`)
// IsValidTopicName checks a topic name for correctness
func IsValidTopicName(name string) bool {
if len(name) > 32 || len(name) < 1 {
return false
}
return validTopicNameRegex.MatchString(name)
}
// IsValidChannelName checks a channel name for correctness
func IsValidChannelName(name string) bool {
if len(name) > 32 || len(name) < 1 {
return false
}
return validChannelNameRegex.MatchString(name)
}
// ReadResponse is a client-side utility function to read from the supplied Reader
// according to the NSQ protocol spec:
//
// [x][x][x][x][x][x][x][x]...
// | (int32) || (binary)
// | 4-byte || N-byte
// ------------------------...
// size data
func ReadResponse(r io.Reader) ([]byte, error) {
var msgSize int32
// message size
err := binary.Read(r, binary.BigEndian, &msgSize)
if err != nil {
return nil, err
}
// message binary data
buf := make([]byte, msgSize)
_, err = io.ReadFull(r, buf)
if err != nil {
return nil, err
}
return buf, nil
}
// UnpackResponse is a client-side utility function that unpacks serialized data
// according to NSQ protocol spec:
//
// [x][x][x][x][x][x][x][x]...
// | (int32) || (binary)
// | 4-byte || N-byte
// ------------------------...
// frame ID data
//
// Returns a triplicate of: frame type, data ([]byte), error
func UnpackResponse(response []byte) (int32, []byte, error) {
if len(response) < 4 {
return -1, nil, errors.New("length of response is too small")
}
return int32(binary.BigEndian.Uint32(response)), response[4:], nil
}