/
proto_serializer.go
executable file
·48 lines (38 loc) · 1.04 KB
/
proto_serializer.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
package remote
import (
"fmt"
"github.com/gogo/protobuf/proto"
"reflect"
)
type protoSerializer struct{}
func newProtoSerializer() Serializer {
return &protoSerializer{}
}
func (protoSerializer) Serialize(msg interface{}) ([]byte, error) {
if message, ok := msg.(proto.Message); ok {
bytes, err := proto.Marshal(message)
if err != nil {
return nil, err
}
return bytes, nil
}
return nil, fmt.Errorf("msg must be proto.Message")
}
func (protoSerializer) Deserialize(typeName string, bytes []byte) (interface{}, error) {
protoType := proto.MessageType(typeName)
if protoType == nil {
return nil, fmt.Errorf("Unknown message type %v", typeName)
}
t := protoType.Elem()
intPtr := reflect.New(t)
instance := intPtr.Interface().(proto.Message)
proto.Unmarshal(bytes, instance)
return instance, nil
}
func (protoSerializer) GetTypeName(msg interface{}) (string, error) {
if message, ok := msg.(proto.Message); ok {
typeName := proto.MessageName(message)
return typeName, nil
}
return "", fmt.Errorf("msg must be proto.Message")
}