/
serialize.go
59 lines (49 loc) · 1.18 KB
/
serialize.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
package codec
type Type string
const (
JSON Type = "json"
MessagePack Type = "msgpack"
MessagePackExtJS Type = "msgpack#js"
Protobuf Type = "proto"
)
// Serializer 序列化接口
type Serializer interface {
Marshal(msg interface{}) []byte
MarshalBody(msg interface{}) []byte
Unmarshal(data []byte, msg interface{}) error
Unpack(fmt Type, data []byte) (string, []byte)
}
// IWrapper 消息外包装
type IWrapper interface {
GetType() string
GetData() []byte
}
type extInfo struct {
Setup func()
Wrapper IWrapper
}
var (
// _format 序列化格式
_format = map[Type]Serializer{
JSON: &SerialJSON{},
MessagePack: &SerialMessagePack{},
MessagePackExtJS: &SerialMessagePack{},
Protobuf: &SerialProtobuf{},
}
_ext = map[Type]extInfo{
MessagePackExtJS: {Setup: setupJSMessagePack, Wrapper: &MessagePackJSWrapper{}},
}
)
// Register 注册协议
func Register(fmt Type, codec Serializer) {
_format[fmt] = codec
}
// GetFormat 获取序列化格式
func Get(fmt Type) Serializer {
return _format[fmt]
}
func init() {
for _, e := range _ext {
e.Setup()
}
}