-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.go
95 lines (76 loc) · 2.06 KB
/
encoder.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
package hevent
import (
"bytes"
"encoding/json"
"errors"
"github.com/kamva/tracer"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
// Encoder encode and decode the event payload.
type Encoder interface {
// Name returns the Encoder name.
Name() string
Encode(interface{}) ([]byte, error)
Decoder([]byte) Decoder
}
// Decoder is event payload decoder.
type Decoder interface {
// Decode decodes payload to the provided value.
Decode(val interface{}) error
}
// protobufEncoder is protobuf implementation of the Encoder
type protobufEncoder struct{}
type protobufDecoder struct {
b []byte
}
// jsonEncoder is json implementation of the Encoder.
type jsonEncoder struct{}
const (
jsonEncoderName = "json"
protobufEncoderName = "protobuf"
)
var encoders = map[string]Encoder{
jsonEncoderName: NewJsonEncoder(),
protobufEncoderName: NewProtobufEncoder(),
}
var (
protobufTypeErr = errors.New("the provided value is not protobuf message")
)
func (m jsonEncoder) Name() string {
return jsonEncoderName
}
func (m jsonEncoder) Encode(v interface{}) ([]byte, error) {
return json.Marshal(v)
}
func (m jsonEncoder) Decoder(buf []byte) Decoder {
return json.NewDecoder(bytes.NewReader(buf))
}
func (m protobufEncoder) Name() string {
return protobufEncoderName
}
func (m protobufEncoder) Encode(v interface{}) ([]byte, error) {
// I think we can use message v2 here.
pb, ok := v.(proto.Message)
if !ok {
return nil, tracer.Trace(protobufTypeErr)
}
return protojson.Marshal(pb)
}
func (m protobufEncoder) Decoder(buf []byte) Decoder {
return &protobufDecoder{b: buf}
}
func (p *protobufDecoder) Decode(val interface{}) error {
return protojson.Unmarshal(p.b, val.(proto.Message))
}
// NewJsonEncoder returns new instance of the json encoder.
func NewJsonEncoder() Encoder {
return &jsonEncoder{}
}
// NewProtobufEncoder returns new instance of the protobuf encoder.
func NewProtobufEncoder() Encoder {
return &protobufEncoder{}
}
var _ Encoder = jsonEncoder{}
var _ Encoder = protobufEncoder{}
var _ Decoder = &protobufDecoder{}