-
Notifications
You must be signed in to change notification settings - Fork 32
/
types.go
61 lines (53 loc) · 1.14 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
package statuscake
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strconv"
)
type jsonNumberString string
func (v *jsonNumberString) UnmarshalJSON(b []byte) error {
if err := v.unmarshalAsInt(b); err == nil {
return nil
}
if err := v.unmarshalAsString(b); err == nil {
return nil
}
return fmt.Errorf("cannot unmarshal value that is neither a number nor a string: %s", truncate(b, 30))
}
func (v *jsonNumberString) unmarshalAsInt(b []byte) error {
if bytes.Equal(b, []byte(`null`)) {
return errors.New("cannot unmarshal JSON null to Go int")
}
var vv int
if err := json.Unmarshal(b, &vv); err != nil {
return err
}
*v = jsonNumberString(strconv.Itoa(vv))
return nil
}
func (v *jsonNumberString) unmarshalAsString(b []byte) error {
var vv string
if err := json.Unmarshal(b, &vv); err != nil {
return err
}
*v = jsonNumberString(vv)
return nil
}
const truncateEllipses = "..."
func truncate(b []byte, max int) []byte {
lte := len(truncateEllipses)
min := lte + 3
if max < min {
max = min
}
if len(b) > max {
t := make([]byte, max)
n := max - lte
copy(t, b[0:n])
copy(t[n:], truncateEllipses)
return t
}
return b
}