/
protocol.go
69 lines (60 loc) · 1.62 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
package connector
import (
"fmt"
"io"
"strings"
)
const (
// https://www.tarantool.io/en/doc/1.10/dev_guide/internals_index/#greeting-packet
greetingSize = 128
)
const (
binaryStr = "Binary"
plainStr = "Lua console"
)
// Protocol defines a set of supported protocols for a connect.
type Protocol int
const (
// IPROTO.
BinaryProtocol Protocol = iota
// Plain text messages.
TextProtocol
)
// String returns a string representation of the protocol.
func (protocol Protocol) String() string {
switch protocol {
case BinaryProtocol:
return binaryStr
case TextProtocol:
return plainStr
default:
panic("Unknown protocol")
}
}
// GetProtocol gets a protocol name from the reader greeting. See:
// https://github.com/tarantool/tarantool/blob/8dcefeb2bf5291487496d168cb81f5b6082a2af0/test/unit/xrow.cc#L92-L123
func GetProtocol(reader io.Reader) (Protocol, error) {
greeting := make([]byte, greetingSize)
if _, err := reader.Read(greeting); err != nil {
err = fmt.Errorf("failed to read Tarantool greeting: %w", err)
return BinaryProtocol, err
}
if protocol, ok := ParseProtocol(string(greeting)); !ok {
err := fmt.Errorf("failed to parse Tarantool greeting: %s", greeting)
return BinaryProtocol, err
} else {
return protocol, nil
}
}
// ParseProtocol parses a protocol name from a Tarantool greeting.
func ParseProtocol(greeting string) (Protocol, bool) {
if strings.HasPrefix(greeting, "Tarantool ") {
switch {
case strings.Contains(greeting, "("+binaryStr+")"):
return BinaryProtocol, true
case strings.Contains(greeting, "("+plainStr+")"):
return TextProtocol, true
}
}
return BinaryProtocol, false
}