-
Notifications
You must be signed in to change notification settings - Fork 8
/
utils.go
127 lines (104 loc) · 2.22 KB
/
utils.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package upcloud
import (
"encoding/json"
"time"
)
// Constants
const (
True Boolean = 1
False Boolean = -1
Empty Boolean = 0
)
// Boolean is a custom boolean type that allows
// for custom marshalling and unmarshalling and
// for an empty value that isn't false so we can
// distinguish between true, false and not set.
type Boolean int
// UnmarshalJSON is a custom unmarshaller that deals with
// deeply embedded values.
func (b *Boolean) UnmarshalJSON(buf []byte) error {
str := string(buf)
if str == `true` ||
str == `"true"` ||
str == `"yes"` ||
str == `1` ||
str == `"1"` {
(*b) = 1
return nil
}
(*b) = -1
return nil
}
// MarshalJSON is a custom unmarshaller that deals with
// deeply embedded values.
func (b *Boolean) MarshalJSON() ([]byte, error) {
if (*b) == 1 {
return []byte(`"yes"`), nil
}
return []byte(`"no"`), nil
}
// Bool converts to a standard bool value
func (b *Boolean) Bool() bool {
return (*b) >= True
}
// Empty checks if this bool is empty
func (b *Boolean) Empty() bool {
return (*b) == Empty
}
// String returns a string representation
func (b *Boolean) String() string {
if (*b) >= True {
return "True"
}
if (*b) <= False {
return "False"
}
return "Empty"
}
// FromBool converts from a standard bool values
func FromBool(v bool) Boolean {
if v {
return True
}
return False
}
func StringPtr(v string) *string {
return &v
}
func BoolPtr(v bool) *bool {
return &v
}
func Float64Ptr(v float64) *float64 {
return &v
}
func IntPtr(v int) *int {
return &v
}
func TimePtr(v time.Time) *time.Time {
return &v
}
// ServerUUIDSlice is a slice of string.
// It exists to allow for a custom JSON unmarshaller.
type ServerUUIDSlice []string
// UnmarshalJSON is a custom unmarshaller that deals with
// deeply embedded values.
func (s *ServerUUIDSlice) UnmarshalJSON(b []byte) error {
v := struct {
ServerUUIDs []string `json:"server"`
}{}
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
(*s) = v.ServerUUIDs
return nil
}
// MarshalJSON is a custom marshaller that deals with deeply embedded values.
func (s *ServerUUIDSlice) MarshalJSON() ([]byte, error) {
v := struct {
ServerUUIDs []string `json:"server"`
}{
ServerUUIDs: *s,
}
return json.Marshal(&v)
}