forked from omniboost/go-fortnox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcustom_types.go
82 lines (67 loc) · 1.53 KB
/
custom_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
package fortnox
import (
"encoding/json"
"strconv"
)
// StringIsh exists because Fortnox sends back integers unquoted even if underlying type is string
type StringIsh string
func (f *StringIsh) UnmarshalJSON(data []byte) error {
var receiver string
if len(data) == 0 {
return nil
}
if data[0] != '"' {
quoted := strconv.Quote(string(data))
data = []byte(quoted)
}
if err := json.Unmarshal(data, &receiver); err != nil {
return err
}
*f = StringIsh(receiver)
return nil
}
// FloatIsh type to allow unmarshalling from either string or float
type FloatIsh float64
func unmarshalIsh(data []byte, receiver interface{}) error {
if len(data) == 0 {
return nil
}
if data[0] == '"' {
data = data[1:]
data = data[:len(data)-1]
}
if len(data) < 1 {
return nil
}
return json.Unmarshal(data, receiver)
}
// Float64 gets the value as float64
func (f *FloatIsh) Float64() float64 {
if f == nil {
return 0.0
}
return float64(*f)
}
// UnmarshalJSON to allow unmarshalling from either string or float
func (f *FloatIsh) UnmarshalJSON(data []byte) error {
var newF float64
err := unmarshalIsh(data, &newF)
*f = FloatIsh(newF)
return err
}
// IntIsh type to allow unmarshalling from either string or int
type IntIsh int
// Int gets the value as int
func (f *IntIsh) Int() int {
if f == nil {
return 0
}
return int(*f)
}
// UnmarshalJSON to allow unmarshalling from either string or int
func (f *IntIsh) UnmarshalJSON(data []byte) error {
var newI int
err := unmarshalIsh(data, &newI)
*f = IntIsh(newI)
return err
}