-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathlist.go
52 lines (42 loc) · 1.03 KB
/
list.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
package jsh
import (
"encoding/json"
"fmt"
"net/http"
)
// List is just a wrapper around an object array that implements Sendable
type List []*Object
/*
Validate ensures that List is JSON API compatible.
*/
func (list List) Validate(r *http.Request, response bool) *Error {
for _, object := range list {
err := object.Validate(r, response)
if err != nil {
return err
}
}
return nil
}
/*
UnmarshalJSON allows us to manually decode a list via the json.Unmarshaler
interface.
*/
func (list *List) UnmarshalJSON(rawData []byte) error {
// Create a sub-type here so when we call Unmarshal below, we don't recursively
// call this function over and over
type UnmarshalList List
// if our "List" is a single object, modify the JSON to make it into a list
// by wrapping with "[ ]"
if rawData[0] == '{' {
rawData = []byte(fmt.Sprintf("[%s]", rawData))
}
newList := UnmarshalList{}
err := json.Unmarshal(rawData, &newList)
if err != nil {
return err
}
convertedList := List(newList)
*list = convertedList
return nil
}