forked from asynkron/protoactor-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proto_serializer.go
61 lines (47 loc) · 1.39 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
49
50
51
52
53
54
55
56
57
58
59
60
61
package remote
import (
"fmt"
spb "google.golang.org/genproto/googleapis/rpc/status"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
)
type protoSerializer struct{}
func newProtoSerializer() *protoSerializer {
return &protoSerializer{}
}
func (p *protoSerializer) Serialize(msg interface{}) ([]byte, error) {
if message, ok := msg.(*status.Status); ok {
msg = message.Proto()
}
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 (p *protoSerializer) Deserialize(typeName string, bytes []byte) (interface{}, error) {
n, _ := protoregistry.GlobalTypes.FindMessageByName(protoreflect.FullName(typeName))
pm := n.New().Interface()
if err := proto.Unmarshal(bytes, pm); err != nil {
return nil, err
}
if message, ok := pm.(*spb.Status); ok {
return status.FromProto(message), nil
}
return pm, nil
}
func (protoSerializer) GetTypeName(msg interface{}) (string, error) {
if message, ok := msg.(*status.Status); ok {
msg = message.Proto()
}
if message, ok := msg.(proto.Message); ok {
typeName := proto.MessageName(message)
return string(typeName), nil
}
return "", fmt.Errorf("msg must be proto.Message")
}