-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathprotocol.go
97 lines (80 loc) · 1.88 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
89
90
91
92
93
94
95
96
97
package main
import (
"bytes"
)
type MessageType int
type FieldType int
const (
Call MessageType = 1
Reply = 2
Exception = 3
Oneway = 4
)
const (
BOOL FieldType = 2
BYTE = 3
DOUBLE = 4
I16 = 6
I32 = 8
I64 = 10
STRING = 11
STRUCT = 12
MAP = 13
SET = 14
LIST = 15
)
type BinaryProtocol struct {
framed bool
buf *bytes.Buffer
}
func NewBinaryProtocol(framed bool) *BinaryProtocol {
b := &BinaryProtocol{framed: framed, buf: bytes.NewBuffer(make([]byte, 0))}
b.WriteInt32(0)
return b
}
func (bp *BinaryProtocol) BeginMessage(name string, msgType MessageType, seqId int) {
bp.buf.WriteByte(0x80)
bp.buf.WriteByte(0x01)
bp.buf.WriteByte(0)
bp.buf.WriteByte(byte(msgType))
bp.WriteString(name)
bp.WriteInt32(seqId)
}
func (bp *BinaryProtocol) EndMessage() {
}
func (bp *BinaryProtocol) BeginStruct() {
bp.buf.WriteByte(STRUCT)
}
func (bp *BinaryProtocol) EndStruct() {
}
func (bp *BinaryProtocol) BeginField(fieldType FieldType, fieldId int) {
bp.buf.WriteByte(byte(fieldType))
bp.buf.WriteByte(byte((fieldId >> 16) & 0xff))
bp.buf.WriteByte(byte(fieldId & 0xff))
}
func (bp *BinaryProtocol) EndField() {
}
func (bp *BinaryProtocol) StopField() {
bp.buf.WriteByte(0)
}
func (bp *BinaryProtocol) WriteInt32(value int) {
bp.buf.WriteByte(byte((value >> 24) & 0xff))
bp.buf.WriteByte(byte((value >> 16) & 0xff))
bp.buf.WriteByte(byte((value >> 8) & 0xff))
bp.buf.WriteByte(byte(value & 0xff))
}
func (bp *BinaryProtocol) WriteString(s string) {
b := []byte(s)
bp.WriteBytes(b)
}
func (bp *BinaryProtocol) WriteBytes(b []byte) {
bp.WriteInt32(len(b))
bp.buf.Write(b)
}
func (bp *BinaryProtocol) ToMessage() *Message {
b := bp.buf.Bytes()
if bp.framed {
writeInt(b, 0, len(b)-4)
}
return NewMessage(b)
}