-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
55 lines (45 loc) · 971 Bytes
/
util.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
package shelly
import (
"encoding/json"
"errors"
"strings"
)
// NullString is similar to a *string but will encode to the JSON null value if empty, but
// *NullString(nil) will be omitted w/ omitempty flag.
type NullString string
func NewNullString(s string) *NullString {
n := NullString(s)
return &n
}
func (n *NullString) String() string {
return string(*n)
}
func (n *NullString) UnmarshalJSON(b []byte) error {
s := strings.TrimSpace(string(b))
if s == "null" {
return nil
}
if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' {
return errors.New("JSON string type expected")
}
*n = NullString(s[1 : len(s)-1])
return nil
}
func (n *NullString) MarshalJSON() ([]byte, error) {
if n == nil || *n == "" {
return []byte("null"), nil
}
return json.Marshal(*n)
}
func StrPtr(s string) *string {
return &s
}
func IntPtr(i int) *int {
return &i
}
func Float64Ptr(f float64) *float64 {
return &f
}
func BoolPtr(b bool) *bool {
return &b
}