-
Notifications
You must be signed in to change notification settings - Fork 0
/
proto.go
56 lines (43 loc) · 1.12 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
package proto
import (
"github.com/pkg/errors"
"github.com/golang/protobuf/proto"
"github.com/charlesbases/library/codec"
"github.com/charlesbases/library/content"
)
// ErrInvalidType .
var ErrInvalidType = errors.New("proto: not implemented")
const mess = "[ProtoMessage]"
// Marshaler default codec.Marshaler
var Marshaler = NewMarshaler()
type protoMarshaler struct {
*codec.MarshalOptions
}
// NewMarshaler .
func NewMarshaler(opts ...func(o *codec.MarshalOptions)) codec.Marshaler {
var options = new(codec.MarshalOptions)
for _, opt := range opts {
opt(options)
}
return &protoMarshaler{MarshalOptions: options}
}
// Marshal .
func (*protoMarshaler) Marshal(v interface{}) ([]byte, error) {
if pv, ok := v.(proto.Message); ok {
return proto.Marshal(pv)
} else {
return nil, ErrInvalidType
}
}
// Unmarshal .
func (*protoMarshaler) Unmarshal(data []byte, v interface{}) error {
return proto.Unmarshal(data, v.(proto.Message))
}
// RawMessage .
func (c *protoMarshaler) RawMessage(data []byte) string {
return mess
}
// ContentType .
func (c *protoMarshaler) ContentType() content.Type {
return content.Proto
}