forked from asynkron/protoactor-go
/
json_serializer.go
73 lines (61 loc) · 1.54 KB
/
json_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
62
63
64
65
66
67
68
69
70
71
72
73
package remote
import (
"bytes"
"fmt"
"github.com/gogo/protobuf/jsonpb"
"github.com/gogo/protobuf/proto"
"reflect"
)
type jsonSerializer struct {
jsonpb.Marshaler
jsonpb.Unmarshaler
}
func newJsonSerializer() Serializer {
return &jsonSerializer{
Marshaler: jsonpb.Marshaler{},
Unmarshaler: jsonpb.Unmarshaler{
AllowUnknownFields: true,
},
}
}
func (j *jsonSerializer) Serialize(msg interface{}) ([]byte, error) {
if message, ok := msg.(*JsonMessage); ok {
return []byte(message.Json), nil
} else if message, ok := msg.(proto.Message); ok {
str, err := j.Marshaler.MarshalToString(message)
if err != nil {
return nil, err
}
return []byte(str), nil
}
return nil, fmt.Errorf("msg must be proto.Message")
}
func (j *jsonSerializer) Deserialize(typeName string, b []byte) (interface{}, error) {
protoType := proto.MessageType(typeName)
if protoType == nil {
m := &JsonMessage{
TypeName: typeName,
Json: string(b),
}
return m, nil
}
t := protoType.Elem()
intPtr := reflect.New(t)
instance, ok := intPtr.Interface().(proto.Message)
if ok {
r := bytes.NewReader(b)
j.Unmarshaler.Unmarshal(r, instance)
return instance, nil
} else {
return nil, fmt.Errorf("msg must be proto.Message")
}
}
func (j *jsonSerializer) GetTypeName(msg interface{}) (string, error) {
if message, ok := msg.(*JsonMessage); ok {
return message.TypeName, nil
} else if message, ok := msg.(proto.Message); ok {
typeName := proto.MessageName(message)
return typeName, nil
}
return "", fmt.Errorf("msg must be proto.Message")
}