/
encoding.go
72 lines (53 loc) · 1.68 KB
/
encoding.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
package stream
import (
"fmt"
)
type EncodingType string
const (
EncodingJson EncodingType = "application/json"
EncodingProtobuf EncodingType = "application/x-protobuf"
)
func (s EncodingType) String() string {
return string(s)
}
var _ fmt.Stringer = EncodingType("")
var defaultMessageBodyEncoding = EncodingJson
func WithDefaultMessageBodyEncoding(encoding EncodingType) {
defaultMessageBodyEncoding = encoding
}
type MessageBodyEncoder interface {
Encode(data interface{}) ([]byte, error)
Decode(data []byte, out interface{}) error
}
var messageBodyEncoders = map[EncodingType]MessageBodyEncoder{
EncodingJson: new(jsonEncoder),
EncodingProtobuf: new(protobufEncoder),
}
func AddMessageBodyEncoder(encoding EncodingType, encoder MessageBodyEncoder) {
messageBodyEncoders[encoding] = encoder
}
func EncodeMessage(encoding EncodingType, data interface{}) ([]byte, error) {
if encoding == "" {
return nil, fmt.Errorf("no encoding provided to encode message")
}
encoder, ok := messageBodyEncoders[encoding]
if !ok {
return nil, fmt.Errorf("there is no message body encoder available for encoding '%s'", encoding)
}
body, err := encoder.Encode(data)
if err != nil {
return nil, fmt.Errorf("can not encode message body with encoding '%s': %w", encoding, err)
}
return body, nil
}
func DecodeMessage(encoding EncodingType, data []byte, out interface{}) error {
encoder, ok := messageBodyEncoders[encoding]
if !ok {
return fmt.Errorf("there is no message body decoder available for encoding '%s'", encoding)
}
err := encoder.Decode(data, out)
if err != nil {
return fmt.Errorf("can not decode message body with encoding '%s': %w", encoding, err)
}
return nil
}