-
Notifications
You must be signed in to change notification settings - Fork 0
/
must.go
71 lines (59 loc) · 1.19 KB
/
must.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
package jflat
import (
"encoding/json"
"reflect"
)
var _ Flatten = (*mustFlattenList)(nil)
func MustFlatten(i ...interface{}) Flatten {
list := mustFlattenList(i)
return &list
}
type mustFlattenList []interface{}
func (list mustFlattenList) MarshalJSON() ([]byte, error) {
var result []byte
var errSet ErrorSet
for i := range list {
src := list[i]
data, err := json.Marshal(src)
if err != nil {
errSet.Err = append(errSet.Err, &MustFlattenError{
Type: reflect.TypeOf(src),
Index: i,
Cause: err,
})
}
if len(result) > 0 {
data[0] = ','
result = append(result[:len(result)-1], data...)
} else {
result = data
}
}
var err error
if len(errSet.Err) > 0 {
err = &errSet
}
return result, err
}
func (list *mustFlattenList) UnmarshalJSON(data []byte) error {
var errSet ErrorSet
for i := range *list {
dst := (*list)[i]
err := json.Unmarshal(data, dst)
if err != nil {
errSet.Err = append(errSet.Err, &MustFlattenError{
Type: reflect.TypeOf(dst),
Index: i,
Cause: err,
})
}
}
if len(errSet.Err) > 0 {
return &errSet
}
return nil
}
func (list *mustFlattenList) Add(i interface{}) error {
*list = append(*list, i)
return nil
}