-
Notifications
You must be signed in to change notification settings - Fork 6
/
proto.go
68 lines (54 loc) · 1.96 KB
/
proto.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
package serialize
import (
"fmt"
"reflect"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
type (
ProtoSerializer interface {
ToBytes(proto.Message) ([]byte, error)
FromBytes(serialized []byte, target proto.Message) (proto.Message, error)
}
BinaryProtoSerializer struct {
}
JSONProtoSerializer struct {
UseProtoNames bool // to use proto field name instead of lowerCamelCase name in JSON field names
}
)
func (ps *BinaryProtoSerializer) ToBytes(entry proto.Message) ([]byte, error) {
return BinaryProtoMarshal(entry)
}
func (ps *BinaryProtoSerializer) FromBytes(serialized []byte, target proto.Message) (proto.Message, error) {
return BinaryProtoUnmarshal(serialized, target)
}
func (js *JSONProtoSerializer) ToBytes(entry proto.Message) ([]byte, error) {
mo := &protojson.MarshalOptions{UseProtoNames: js.UseProtoNames, EmitUnpopulated: true}
return JSONProtoMarshal(entry, mo)
}
func (js *JSONProtoSerializer) FromBytes(serialized []byte, target proto.Message) (proto.Message, error) {
return JSONProtoUnmarshal(serialized, target)
}
func BinaryProtoMarshal(entry proto.Message) ([]byte, error) {
return proto.Marshal(proto.Clone(entry))
}
func JSONProtoMarshal(entry proto.Message, mo *protojson.MarshalOptions) ([]byte, error) {
return mo.Marshal(proto.Clone(entry))
}
// BinaryProtoUnmarshal r unmarshalls []byte as proto.Message to pointer, and returns value pointed to
func BinaryProtoUnmarshal(bb []byte, messageType proto.Message) (message proto.Message, err error) {
msg := proto.Clone(messageType)
err = proto.Unmarshal(bb, msg)
if err != nil {
return nil, fmt.Errorf(`unmarshal to proto=%s: %w`, reflect.TypeOf(messageType), err)
}
return msg, nil
}
func JSONProtoUnmarshal(json []byte, messageType proto.Message) (message proto.Message, err error) {
msg := proto.Clone(messageType)
err = protojson.Unmarshal(json, msg)
if err != nil {
return nil, fmt.Errorf(`json proto unmarshal: %w`, err)
}
return msg, nil
}