-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtypes.go
More file actions
101 lines (87 loc) · 2.09 KB
/
types.go
File metadata and controls
101 lines (87 loc) · 2.09 KB
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 cloudloyalty_client
import (
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"time"
)
type IntAsIntOrString int
// UnmarshalJSON decodes int or string into int without triggering an error.
// If string is not a valid number, assumes 0.
func (i *IntAsIntOrString) UnmarshalJSON(b []byte) error {
if len(b) >= 2 && b[0] == '"' && b[len(b)-1] == '"' {
// empty string is considered as zero
if len(b) == 2 {
*i = IntAsIntOrString(0)
return nil
}
b = b[1 : len(b)-1]
}
val, err := strconv.ParseFloat(string(b), 64)
if err != nil {
val = 0
}
*i = IntAsIntOrString(val)
return nil
}
type ExtraFields map[string]any
type IntOrAuto struct {
json.Unmarshaler
Auto bool
Value Int
}
func (i *IntOrAuto) UnmarshalJSON(v []byte) error {
if strings.EqualFold(string(v), "\"auto\"") {
i.Auto = true
i.Value = 0
return nil
}
i.Auto = false
return i.Value.UnmarshalJSON(v)
}
func (i *IntOrAuto) MarshalJSON() ([]byte, error) {
if i.Auto {
return []byte("\"auto\""), nil
}
return []byte(strconv.Itoa(int(i.Value))), nil
}
type Int int
func (i *Int) UnmarshalJSON(v []byte) error {
// it is allowed for value to be a float with zero fractional part, e.g. 1.0
f, err := strconv.ParseFloat(string(v), 64)
if err != nil {
return err
}
iv, frac := math.Modf(f)
if frac != 0 {
return fmt.Errorf("unexpected fractional part in integer value: %f", f)
}
*i = Int(iv)
return nil
}
type ValidRangeTime time.Time
var (
TimeValidRangeStart = time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)
TimeValidRangeEnd = time.Date(2040, 1, 1, 0, 0, 0, 0, time.UTC).Add(-time.Second)
)
func (v *ValidRangeTime) UnmarshalJSON(b []byte) error {
t := (*time.Time)(v)
if err := t.UnmarshalJSON(b); err != nil {
return err
}
if t.Before(TimeValidRangeStart) || t.After(TimeValidRangeEnd) {
return fmt.Errorf(
"date %s is out of valid range (%s to %s)",
t.Format(time.RFC3339),
TimeValidRangeStart.Format(time.RFC3339),
TimeValidRangeEnd.Format(time.RFC3339),
)
}
return nil
}
func (v *ValidRangeTime) MarshalJSON() ([]byte, error) {
t := (*time.Time)(v)
return t.MarshalJSON()
}