This repository has been archived by the owner on Sep 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage.go
111 lines (91 loc) · 2.31 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
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package kafka
import (
"fmt"
"strconv"
eventV1 "github.com/AlpacaLabs/protorepo-event-go/alpacalabs/event/v1"
"github.com/golang/protobuf/proto"
"github.com/segmentio/kafka-go"
)
const (
HeaderForTraceID = "trace_id"
HeaderForSampled = "sampled"
HeaderForEventID = "event_id"
)
type Message struct {
Headers map[string][]byte
Payload []byte
}
func NewMessage(traceInfo eventV1.TraceInfo, eventInfo eventV1.EventInfo, payload []byte) (Message, error) {
m := Message{
Headers: make(map[string][]byte),
}
m.Payload = payload
m.Headers[HeaderForTraceID] = []byte(traceInfo.TraceId)
m.Headers[HeaderForSampled] = []byte(strconv.FormatBool(traceInfo.Sampled))
m.Headers[HeaderForEventID] = []byte(eventInfo.EventId)
return m, nil
}
func (m Message) ToKafkaMessage() kafka.Message {
var headers []kafka.Header
for k, v := range m.Headers {
headers = append(headers, kafka.Header{
Key: k,
Value: v,
})
}
return kafka.Message{
Headers: headers,
Value: m.Payload,
}
}
func fromMessage(in kafka.Message) Message {
headers := make(map[string][]byte)
for _, h := range in.Headers {
headers[h.Key] = h.Value
}
return Message{
Headers: headers,
Payload: in.Value,
}
}
func (m Message) GetString(key string) (string, error) {
if v, ok := m.Headers[key]; ok {
return string(v), nil
}
return "", fmt.Errorf("no message header found for key: %s", key)
}
func (m Message) GetBool(key string) (bool, error) {
s, err := m.GetString(key)
if err != nil {
return false, err
}
b, err := strconv.ParseBool(s)
if err != nil {
return false, fmt.Errorf("failed to parse bool for key: %s: %w", key, err)
}
return b, nil
}
func (m Message) GetTraceInfo() (traceInfo eventV1.TraceInfo, err error) {
if traceID, err := m.GetString(HeaderForTraceID); err != nil {
return traceInfo, err
} else {
traceInfo.TraceId = traceID
}
if sampled, err := m.GetBool(HeaderForSampled); err != nil {
return traceInfo, err
} else {
traceInfo.Sampled = sampled
}
return traceInfo, err
}
func (m Message) GetEventInfo() (eventInfo eventV1.EventInfo, err error) {
if eventID, err := m.GetString(HeaderForEventID); err != nil {
return eventInfo, err
} else {
eventInfo.EventId = eventID
}
return eventInfo, err
}
func (m Message) Unmarshal(pb proto.Message) error {
return proto.Unmarshal(m.Payload, pb)
}