-
Notifications
You must be signed in to change notification settings - Fork 1
/
proto.go
120 lines (96 loc) · 2.18 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// Package proto provides a proto codec
package proto // import "go.unistack.org/micro-codec-proto/v3"
import (
"io"
pb "go.unistack.org/micro-proto/v3/codec"
"go.unistack.org/micro/v3/codec"
rutil "go.unistack.org/micro/v3/util/reflect"
"google.golang.org/protobuf/proto"
)
type protoCodec struct {
opts codec.Options
}
var _ codec.Codec = &protoCodec{}
const (
flattenTag = "flatten"
)
func (c *protoCodec) Marshal(v interface{}, opts ...codec.Option) ([]byte, error) {
if v == nil {
return nil, nil
}
options := c.opts
for _, o := range opts {
o(&options)
}
if nv, nerr := rutil.StructFieldByTag(v, options.TagName, flattenTag); nerr == nil {
v = nv
}
switch m := v.(type) {
case *codec.Frame:
return m.Data, nil
case *pb.Frame:
return m.Data, nil
}
if _, ok := v.(proto.Message); !ok {
return nil, codec.ErrInvalidMessage
}
return proto.Marshal(v.(proto.Message))
}
func (c *protoCodec) Unmarshal(d []byte, v interface{}, opts ...codec.Option) error {
if v == nil || len(d) == 0 {
return nil
}
options := c.opts
for _, o := range opts {
o(&options)
}
if nv, nerr := rutil.StructFieldByTag(v, options.TagName, flattenTag); nerr == nil {
v = nv
}
switch m := v.(type) {
case *codec.Frame:
m.Data = d
return nil
case *pb.Frame:
m.Data = d
return nil
}
if _, ok := v.(proto.Message); !ok {
return codec.ErrInvalidMessage
}
return proto.Unmarshal(d, v.(proto.Message))
}
func (c *protoCodec) ReadHeader(conn io.Reader, m *codec.Message, t codec.MessageType) error {
return nil
}
func (c *protoCodec) ReadBody(conn io.Reader, v interface{}) error {
if v == nil {
return nil
}
buf, err := io.ReadAll(conn)
if err != nil {
return err
} else if len(buf) == 0 {
return nil
}
return c.Unmarshal(buf, v)
}
func (c *protoCodec) Write(conn io.Writer, m *codec.Message, v interface{}) error {
if v == nil {
return nil
}
buf, err := c.Marshal(v)
if err != nil {
return err
} else if len(buf) == 0 {
return codec.ErrInvalidMessage
}
_, err = conn.Write(buf)
return err
}
func (c *protoCodec) String() string {
return "proto"
}
func NewCodec(opts ...codec.Option) codec.Codec {
return &protoCodec{opts: codec.NewOptions(opts...)}
}