/
protobuf.go
53 lines (43 loc) · 1.19 KB
/
protobuf.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
package codec
import (
"github.com/rs/zerolog/log"
"github.com/golang/protobuf/proto"
)
// SerialProtobuf 序列化protobuf
type SerialProtobuf struct{}
// Marshal 序列化
func (c SerialProtobuf) Marshal(msg interface{}) []byte {
m, err := proto.Marshal(msg.(proto.Message))
if err != nil {
log.Error().Err(err).Msg("marshal protobuf data")
return nil
}
m, err = (&ProtoWarpper{Name: typeName(msg), Data: m}).Marshal()
if err != nil {
log.Error().Err(err).Msg("marshal protobuf warpper")
return nil
}
return m
}
func (c SerialProtobuf) MarshalBody(val interface{}) []byte {
m, err := proto.Marshal(val.(proto.Message))
if err != nil {
log.Error().Err(err).Msg("marshal protobuf data")
return nil
}
return m
}
// Unmarshal 反序列化
func (c SerialProtobuf) Unmarshal(data []byte, val interface{}) error {
return proto.Unmarshal(data, val.(proto.Message))
}
// Unpack 解开包装
func (c SerialProtobuf) Unpack(format Type, data []byte) (string, []byte) {
t := &ProtoWarpper{}
err := t.Unmarshal(data)
if err != nil {
log.Error().Err(err).Msg("unmarshal protobuf warpper")
return "", nil
}
return t.Name, t.Data
}