-
Notifications
You must be signed in to change notification settings - Fork 20
/
envelope.go
74 lines (59 loc) · 1.51 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
package utils
import (
"bytes"
)
// Typed is an interface of objects that are marshalled as typed envelopes
type Typed interface {
Type() string
}
type typeOnly struct {
Type string `json:"type" validate:"required"`
}
// TypedEnvelope represents a json blob with a type property
type TypedEnvelope struct {
Type string `json:"type" validate:"required"`
Data []byte `json:"-"`
}
// UnmarshalJSON unmarshals a typed envelope from the given JSON
func (e *TypedEnvelope) UnmarshalJSON(b []byte) error {
t := &typeOnly{}
if err := UnmarshalAndValidate(b, t); err != nil {
return err
}
e.Type = t.Type
e.Data = make([]byte, len(b))
copy(e.Data, b)
return nil
}
// 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
t := &typeOnly{Type: e.Type}
typeBytes, err := JSONMarshal(t)
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
}
return &TypedEnvelope{typed.Type(), typedData}, nil
}