-
Notifications
You must be signed in to change notification settings - Fork 1
/
bool.go
79 lines (67 loc) · 1.49 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package newtype
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"strconv"
"strings"
)
var (
_ json.Unmarshaler = new(Bool)
_ json.Marshaler = Bool(false)
_ driver.Valuer = Bool(false)
_ sql.Scanner = new(Bool)
)
// Bool is a custom defined type for bool.
type Bool bool
// UnmarshalJSON implementing UnmarshalJSON interface.
func (b *Bool) UnmarshalJSON(payload []byte) (err error) {
if IsNullJSON(payload) {
return
}
var value string
value = strings.ToLower(strings.Trim(string(payload), `"`))
var original bool
original, err = strconv.ParseBool(value)
if err != nil {
return
}
*b = Bool(original)
return
}
// MarshalJSON implements the MarshalJSON interface.
func (b Bool) MarshalJSON() (result []byte, err error) {
result, err = json.Marshal(bool(b))
return
}
// Value implements the driver Valuer interface.
func (b Bool) Value() (driver.Value, error) {
return bool(b), nil
}
// Scan implements the Scanner interface.
func (b *Bool) Scan(value interface{}) (err error) {
if value == nil {
*b = false
return
}
var boolVal driver.Value
boolVal, err = driver.Bool.ConvertValue(value)
if err == nil {
*b = Bool(boolVal.(bool))
}
return
}
// FromDB implementing Conversion interface for xorm.
func (b *Bool) FromDB(value []byte) (err error) {
err = b.Scan(value)
return
}
// ToDB implementing Conversion interface for xorm.
func (b Bool) ToDB() (val []byte, err error) {
if bool(b) {
val = []byte{'1'}
} else {
val = []byte{'0'}
}
return
}