-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessage_encoder.go
More file actions
76 lines (60 loc) · 1.41 KB
/
message_encoder.go
File metadata and controls
76 lines (60 loc) · 1.41 KB
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
package rabbitmq
import (
"encoding/json"
"errors"
"google.golang.org/protobuf/proto"
)
const (
ProtobufContentType = "application/protobuf"
JsonContentType = "application/json"
)
var (
ErrorIncorrectMessageType = errors.New("message to encoding has incorrect type")
)
type MessageEncoder interface {
GetContentType() string
Marshal(in interface{}) ([]byte, error)
Unmarshal(in []byte, v interface{}) error
}
type ProtobufEncoder struct {
ContentType string
}
type JsonEncoder struct {
ContentType string
}
func NewProtobufEncoder() MessageEncoder {
return &ProtobufEncoder{
ContentType: ProtobufContentType,
}
}
func NewJsonEncoder() MessageEncoder {
return &JsonEncoder{
ContentType: JsonContentType,
}
}
func (m *ProtobufEncoder) Marshal(in interface{}) ([]byte, error) {
msg, ok := in.(proto.Message)
if !ok {
return nil, ErrorIncorrectMessageType
}
return proto.Marshal(msg)
}
func (m *ProtobufEncoder) Unmarshal(in []byte, v interface{}) error {
msg, ok := v.(proto.Message)
if !ok {
return ErrorIncorrectMessageType
}
return proto.Unmarshal(in, msg)
}
func (m *ProtobufEncoder) GetContentType() string {
return m.ContentType
}
func (m *JsonEncoder) Marshal(in interface{}) ([]byte, error) {
return json.Marshal(in)
}
func (m *JsonEncoder) Unmarshal(in []byte, v interface{}) error {
return json.Unmarshal(in, v)
}
func (m *JsonEncoder) GetContentType() string {
return m.ContentType
}