/
codec.go
90 lines (70 loc) · 2.16 KB
/
codec.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
package codec
import (
"encoding/json"
"fmt"
"reflect"
proto "github.com/gogo/protobuf/proto"
pb "github.com/golang/protobuf/proto"
"github.com/vmihailenco/msgpack"
)
// Codec defines the interface that decode/encode payload.
type Codec interface {
Encode(i interface{}) ([]byte, error)
Decode(data []byte, i interface{}) error
}
// ByteCodec uses raw slice pf bytes and don't encode/decode.
type ByteCodec struct{}
// Encode returns raw slice of bytes.
func (c ByteCodec) Encode(i interface{}) ([]byte, error) {
if data, ok := i.([]byte); ok {
return data, nil
}
return nil, fmt.Errorf("%T is not a []byte", i)
}
// Decode returns raw slice of bytes.
func (c ByteCodec) Decode(data []byte, i interface{}) error {
reflect.Indirect(reflect.ValueOf(i)).SetBytes(data)
return nil
}
// JSONCodec uses json marshaler and unmarshaler.
type JSONCodec struct{}
// Encode encodes an object into slice of bytes.
func (c JSONCodec) Encode(i interface{}) ([]byte, error) {
return json.Marshal(i)
}
// Decode decodes an object from slice of bytes.
func (c JSONCodec) Decode(data []byte, i interface{}) error {
return json.Unmarshal(data, i)
}
// PBCodec uses protobuf marshaler and unmarshaler.
type PBCodec struct{}
// Encode encodes an object into slice of bytes.
func (c PBCodec) Encode(i interface{}) ([]byte, error) {
if m, ok := i.(proto.Marshaler); ok {
return m.Marshal()
}
if m, ok := i.(pb.Message); ok {
return pb.Marshal(m)
}
return nil, fmt.Errorf("%T is not a proto.Marshaler", i)
}
// Decode decodes an object from slice of bytes.
func (c PBCodec) Decode(data []byte, i interface{}) error {
if m, ok := i.(proto.Unmarshaler); ok {
return m.Unmarshal(data)
}
if m, ok := i.(pb.Message); ok {
return pb.Unmarshal(data, m)
}
return fmt.Errorf("%T is not a proto.Unmarshaler", i)
}
// MsgpackCodec uses messagepack marshaler and unmarshaler.
type MsgpackCodec struct{}
// Encode encodes an object into slice of bytes.
func (c MsgpackCodec) Encode(i interface{}) ([]byte, error) {
return msgpack.Marshal(i)
}
// Decode decodes an object from slice of bytes.
func (c MsgpackCodec) Decode(data []byte, i interface{}) error {
return msgpack.Unmarshal(data, i)
}