forked from CyCoreSystems/ari
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmessage.go
69 lines (55 loc) · 1.25 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
package ari
import (
"encoding/json"
"errors"
)
// Message is the first extension of the RawMessage type,
// containing only a Type
type Message struct {
RawMessage
Type string `json:"type"`
}
// NewMessage constructs a Message from a byte slice
func NewMessage(raw []byte) (*Message, error) {
var m Message
raw = append(raw, '\n')
err := json.Unmarshal(raw, &m)
if err != nil {
return &m, err
}
// Set _raw to be our raw bytestream
m._raw = raw
return &m, nil
}
// MessageRawer provides operations to get raw message data
type MessageRawer interface {
SetRaw([]byte)
GetRaw() []byte
}
// RawMessage contains the raw bytes
type RawMessage struct {
_raw []byte // The raw message
}
// DecodeAs converts the current message to
// a new message type
func (m *RawMessage) DecodeAs(v MessageRawer) error {
if v == nil {
return errors.New("empty message")
}
// First, unmarshal raw into the new type
err := json.Unmarshal(m.GetRaw(), v)
if err != nil {
return err
}
// Set the new raw to the old raw
v.SetRaw(m.GetRaw())
return nil
}
// SetRaw sets the raw value of this RawMessage
func (m *RawMessage) SetRaw(raw []byte) {
m._raw = raw
}
// GetRaw gets the raw value of this RawMessage
func (m *RawMessage) GetRaw() []byte {
return m._raw
}