-
Notifications
You must be signed in to change notification settings - Fork 2
/
bool.go
56 lines (48 loc) · 1.08 KB
/
bool.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
package route4me
import (
"errors"
"strings"
)
func UnmarshalJSON(bytes []byte) (bool, error) {
str := string(bytes)
if strings.HasPrefix(str, `"`) && strings.HasSuffix(str, `"`) {
str = str[1 : len(str)-1]
}
if strings.ToLower(str) == "true" || str == "1" {
return true, nil
} else if strings.ToLower(str) == "false" || str == "0" || str == "null" || str == "" {
return false, nil
} else {
return false, errors.New("Can't unmarshall unknown format to boolean " + str)
}
}
type Bool bool
func (b *Bool) UnmarshalJSON(bytes []byte) error {
res, err := UnmarshalJSON(bytes)
if err != nil {
return err
}
*b = Bool(res)
return nil
}
func (b *Bool) MarshalJSON() ([]byte, error) {
if *b == true {
return []byte("true"), nil
}
return []byte("false"), nil
}
type StringBool Bool
func (b *StringBool) UnmarshalJSON(bytes []byte) error {
res, err := UnmarshalJSON(bytes)
if err != nil {
return err
}
*b = StringBool(res)
return nil
}
func (b *StringBool) MarshalJSON() ([]byte, error) {
if *b == true {
return []byte("\"TRUE\""), nil
}
return []byte("\"FALSE\""), nil
}