-
Notifications
You must be signed in to change notification settings - Fork 1
/
message.go
50 lines (41 loc) · 938 Bytes
/
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
package pubsub
func NewMessage(h Header, p ...Payload) Message {
return &message{
header: h,
payloads: p,
}
}
type Message interface {
ToBytes() ([]byte, error)
AppendPayloads(...Payload) error
}
type message struct {
header Header
payloads []Payload
}
func (m *message) ToBytes() ([]byte, error) {
var payloadBytes []byte
for _, payload := range m.payloads {
p, err := payload.ToBytes()
if err != nil {
return nil, err
}
payloadBytes = append(payloadBytes, p...)
}
messageLength := uint16(len(payloadBytes))
m.header.SetLength(messageLength)
var message []byte
header, err := m.header.ToBytes()
if err != nil {
return nil, err
}
message = append(message, header...)
message = append(message, payloadBytes...)
return message, nil
}
func (m *message) AppendPayloads(payloads ...Payload) error {
for _, payload := range payloads {
m.payloads = append(m.payloads, payload)
}
return nil
}