-
Notifications
You must be signed in to change notification settings - Fork 50
/
message.go
64 lines (50 loc) · 1.35 KB
/
message.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
package stream
import (
"fmt"
"github.com/justtrackio/gosoline/pkg/encoding/json"
"github.com/spf13/cast"
)
const (
AttributeSqsMessageId = "sqsMessageId"
AttributeSqsReceiptHandle = "sqsReceiptHandle"
)
type Message struct {
Attributes map[string]string `json:"attributes"`
Body string `json:"body"`
metaData map[string]interface{} `json:"-"`
}
func (m *Message) GetAttributes() map[string]string {
return m.Attributes
}
func (m *Message) MarshalToBytes() ([]byte, error) {
return json.Marshal(*m)
}
func (m *Message) MarshalToString() (string, error) {
bytes, err := json.Marshal(*m)
if err != nil {
return "", err
}
return string(bytes), nil
}
func (m *Message) UnmarshalFromBytes(data []byte) error {
type legacy struct {
Attributes map[string]interface{} `json:"attributes"`
Body string `json:"body"`
}
legacyMsg := &legacy{}
if err := json.Unmarshal(data, legacyMsg); err != nil {
return err
}
m.Attributes = make(map[string]string)
m.Body = legacyMsg.Body
var err error
for k, v := range legacyMsg.Attributes {
if m.Attributes[k], err = cast.ToStringE(v); err != nil {
return fmt.Errorf("can not cast attribute %s=%v to string: %w", k, v, err)
}
}
return nil
}
func (m *Message) UnmarshalFromString(data string) error {
return m.UnmarshalFromBytes([]byte(data))
}