-
Notifications
You must be signed in to change notification settings - Fork 50
/
message_builder.go
85 lines (64 loc) · 2.09 KB
/
message_builder.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
package stream
import (
"fmt"
)
const (
AttributeEncoding = "encoding"
AttributeCompression = "compression"
)
// GetEncodingAttribute returns the encoding attribute if one is set, nil if none is set,
// and an error if the set value is of the wrong type.
func GetEncodingAttribute(attributes map[string]string) *EncodingType {
if attrEncoding, ok := attributes[AttributeEncoding]; ok {
encoding := EncodingType(attrEncoding)
return &encoding
}
return nil
}
// GetCompressionAttribute returns the compression attribute if one is set, nil if none is set,
// and an error if the set value is of the wrong type.
func GetCompressionAttribute(attributes map[string]string) *CompressionType {
if attrCompression, ok := attributes[AttributeCompression]; ok {
compression := CompressionType(attrCompression)
return &compression
}
return nil
}
func NewMessage(body string, attributes ...map[string]string) *Message {
msg := &Message{
Attributes: map[string]string{},
Body: body,
}
for _, attrs := range attributes {
for k, v := range attrs {
msg.Attributes[k] = v
}
}
return msg
}
func NewJsonMessage(body string, attributes ...map[string]string) *Message {
msg := NewMessage(body, attributes...)
msg.Attributes[AttributeEncoding] = EncodingJson.String()
return msg
}
func MarshalJsonMessage(body interface{}, attributes ...map[string]string) (*Message, error) {
data, err := NewJsonEncoder().Encode(body)
if err != nil {
return nil, fmt.Errorf("can not marshal body to json: %w", err)
}
msg := NewJsonMessage(string(data), attributes...)
return msg, nil
}
func NewProtobufMessage(body string, attributes ...map[string]string) *Message {
msg := NewMessage(body, attributes...)
msg.Attributes[AttributeEncoding] = EncodingProtobuf.String()
return msg
}
func MarshalProtobufMessage(body ProtobufEncodable, attributes ...map[string]string) (*Message, error) {
data, err := NewProtobufEncoder().Encode(body)
if err != nil {
return nil, fmt.Errorf("can not marshal body to protobuf: %w", err)
}
msg := NewProtobufMessage(string(data), attributes...)
return msg, nil
}