forked from nyaruka/goflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
envelope.go
78 lines (63 loc) · 1.54 KB
/
envelope.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
package utils
import (
"bytes"
"encoding/json"
)
// Typed is an interface of objects that are marshalled as typed envelopes
type Typed interface {
Type() string
}
// TypedEnvelope represents a json blob with a type property
type TypedEnvelope struct {
Type string `json:"type"`
Data []byte `json:"-"`
}
// UnmarshalJSON unmarshals a typed envelope from the given JSON
func (e *TypedEnvelope) UnmarshalJSON(b []byte) (err error) {
typeE := &struct {
Type string `json:"type"`
}{}
err = json.Unmarshal(b, &typeE)
if err != nil {
return err
}
e.Type = typeE.Type
e.Data = make([]byte, len(b))
copy(e.Data, b)
return err
}
// MarshalJSON marshals this envelope into JSON
func (e *TypedEnvelope) MarshalJSON() ([]byte, error) {
// we want the insert the type into our parent data and return that
typeE := &struct {
Type string `json:"type"`
}{Type: e.Type}
typeBytes, err := JSONMarshal(&typeE)
if err != nil {
return nil, err
}
// empty case {}
if len(e.Data) == 2 {
return typeBytes, nil
}
data := bytes.NewBuffer(typeBytes)
// remove ending }
data.Truncate(data.Len() - 1)
// add ,
data.WriteByte(',')
// copy in our data, skipping over the leading {
data.Write(e.Data[1:])
return data.Bytes(), nil
}
// EnvelopeFromTyped marshals the give object into a typed envelope
func EnvelopeFromTyped(typed Typed) (*TypedEnvelope, error) {
if typed == nil {
return nil, nil
}
typedData, err := JSONMarshal(typed)
if err != nil {
return nil, err
}
envelope := TypedEnvelope{typed.Type(), typedData}
return &envelope, nil
}