-
Notifications
You must be signed in to change notification settings - Fork 318
/
types.go
101 lines (92 loc) · 2.19 KB
/
types.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package types
import (
"encoding/json"
"strconv"
"github.com/pkg/errors"
)
var (
// ErrUnsupportedType is returned if the type is not implemented
ErrUnsupportedType = errors.New("unsupported type")
)
// StrIntArray string array to be used on JSON UnmarshalJSON
type StrIntArray []string
// UnmarshalJSON convert JSON object array of string or
// a string format strings to a golang string array
func (sa *StrIntArray) UnmarshalJSON(data []byte) error {
var jsonObj interface{}
err := json.Unmarshal(data, &jsonObj)
if err != nil {
return errors.Wrap(err, "unmarshal str int array")
}
switch obj := jsonObj.(type) {
case string:
*sa = StrIntArray([]string{obj})
return nil
case int:
*sa = StrIntArray([]string{strconv.Itoa(obj)})
return nil
case []interface{}:
s := make([]string, 0, len(obj))
for _, v := range obj {
switch value := v.(type) {
case string:
s = append(s, value)
case int:
s = append(s, strconv.Itoa(value))
case float64:
s = append(s, strconv.Itoa(int(value)))
default:
return ErrUnsupportedType
}
}
*sa = StrIntArray(s)
return nil
}
return ErrUnsupportedType
}
// StrArray string array to be used on JSON UnmarshalJSON
type StrArray []string
// UnmarshalJSON convert JSON object array of string or
// a string format strings to a golang string array
func (sa *StrArray) UnmarshalJSON(data []byte) error {
var jsonObj interface{}
err := json.Unmarshal(data, &jsonObj)
if err != nil {
return err
}
switch obj := jsonObj.(type) {
case string:
*sa = StrArray([]string{obj})
return nil
case []interface{}:
s := make([]string, 0, len(obj))
for _, v := range obj {
value, ok := v.(string)
if !ok {
return ErrUnsupportedType
}
s = append(s, value)
}
*sa = StrArray(s)
return nil
}
return ErrUnsupportedType
}
type StrBool string
// UnmarshalJSON parses fields that may be numbers or booleans.
func (f *StrBool) UnmarshalJSON(data []byte) error {
var jsonObj interface{}
err := json.Unmarshal(data, &jsonObj)
if err != nil {
return err
}
switch obj := jsonObj.(type) {
case string:
*f = StrBool(obj)
return nil
case bool:
*f = StrBool(strconv.FormatBool(obj))
return nil
}
return ErrUnsupportedType
}