-
Notifications
You must be signed in to change notification settings - Fork 10
/
bool.go
123 lines (103 loc) · 1.9 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
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
package meta
import (
"database/sql/driver"
"encoding/json"
"reflect"
"strconv"
)
//
// Bool
//
type Bool struct {
Val bool
Nullity
Presence
Path string
}
type BoolOptions struct {
Required bool
DiscardBlank bool
Null bool
}
func NewBool(b bool) Bool {
return Bool{b, Nullity{false}, Presence{true}, ""}
}
func (b *Bool) ParseOptions(tag reflect.StructTag) interface{} {
opts := &BoolOptions{
Required: false,
DiscardBlank: true,
Null: false,
}
if tag.Get("meta_required") == "true" {
opts.Required = true
}
if tag.Get("meta_discard_blank") == "false" {
opts.DiscardBlank = false
}
if tag.Get("meta_null") == "true" {
opts.Null = true
}
return opts
}
func (b *Bool) FormValue(value string, options interface{}) Errorable {
opts := options.(*BoolOptions)
if value == "" {
if opts.Null {
b.Present = true
b.Null = true
return nil
}
if opts.Required {
return ErrBlank
}
if !opts.DiscardBlank {
b.Present = true
return ErrBlank
}
return nil
}
if v, err := strconv.ParseBool(value); err == nil {
b.Val = v
b.Present = true
return nil
}
return ErrBool
}
func (b *Bool) JSONValue(path string, i interface{}, options interface{}) Errorable {
opts := options.(*BoolOptions)
b.Path = path
if i == nil {
if opts.Null {
b.Present = true
b.Null = true
return nil
}
if opts.Required || !opts.DiscardBlank {
return ErrBlank
}
return nil
}
switch value := i.(type) {
case string:
return b.FormValue(value, options)
case json.Number:
return b.FormValue(string(value), options)
case bool:
b.Val = value
b.Present = true
return nil
}
return ErrBool
}
func (b Bool) Value() (driver.Value, error) {
if b.Present && !b.Null {
return b.Val, nil
}
return nil, nil
}
func (b Bool) MarshalJSON() ([]byte, error) {
if b.Present && !b.Null {
return MetaJson.Marshal(b.Val)
}
return nullString, nil
}