-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathembeds.go
60 lines (55 loc) · 1.23 KB
/
embeds.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
package haljson
import (
"bytes"
"encoding/json"
"fmt"
"strings"
)
// Embeds holds embedded relations by reltype
type Embeds struct {
Relations map[string][]Resource
}
// MarshalJSON marshals embeds
func (e *Embeds) MarshalJSON() ([]byte, error) {
var bufferData []string
for key, links := range e.Relations {
jsonValue, err := json.Marshal(links)
if err != nil {
return nil, err
}
bufferData = append(bufferData, fmt.Sprintf("\"%s\": %s", key, string(jsonValue)))
}
buffer := bytes.NewBufferString("{")
buffer.WriteString(strings.Join(bufferData, ","))
buffer.WriteString("}")
return buffer.Bytes(), nil
}
// UnmarshalJSON unmarshals embeds
func (e *Embeds) UnmarshalJSON(b []byte) error {
var temp map[string]interface{}
temp = make(map[string]interface{})
err := json.Unmarshal(b, &temp)
if err != nil {
return err
}
e.Relations = make(map[string][]Resource)
for k, v := range temp {
var res []Resource
b, err := json.Marshal(v)
if err != nil {
return err
}
err = json.Unmarshal(b, &res)
if err != nil {
return err
}
e.Relations[k] = res
}
return nil
}
// NewEmbeds creates and initializes Embeds
func NewEmbeds() *Embeds {
e := &Embeds{}
e.Relations = make(map[string][]Resource)
return e
}