forked from gocraft/meta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time.go
113 lines (93 loc) · 1.78 KB
/
time.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
package meta
import (
"database/sql/driver"
"encoding/json"
"reflect"
"time"
)
//
// Time
//
type Time struct {
Val time.Time
Nullity
Presence
}
type TimeOptions struct {
Required bool
DiscardBlank bool
Null bool
Format []string
}
func NewTime(t time.Time) Time {
return Time{t, Nullity{false}, Presence{true}}
}
func (t *Time) ParseOptions(tag reflect.StructTag) interface{} {
opts := &TimeOptions{
Required: false,
DiscardBlank: true,
Null: false,
Format: []string{time.RFC3339},
}
if tag.Get("meta_required") == "true" {
opts.Required = true
}
if tag.Get("meta_null") == "true" {
opts.Null = true
}
if tag.Get("meta_discard_blank") == "false" {
opts.DiscardBlank = false
}
if tag.Get("meta_format") != "" {
opts.Format = []string{tag.Get("meta_format")}
}
return opts
}
func (t *Time) JSONValue(i interface{}, options interface{}) Errorable {
if i == nil {
return t.FormValue("", options)
}
switch value := i.(type) {
case string:
return t.FormValue(value, options)
}
return ErrTime
}
func (t *Time) FormValue(value string, options interface{}) Errorable {
opts := options.(*TimeOptions)
if value == "" {
if opts.Null {
t.Present = true
t.Null = true
return nil
}
if opts.Required {
return ErrBlank
}
if !opts.DiscardBlank {
t.Present = true
return ErrBlank
}
return nil
}
for _, format := range opts.Format {
if v, err := time.Parse(format, value); err == nil {
t.Val = v
t.Present = true
return nil
}
}
return ErrTime
}
func (t Time) Value() (driver.Value, error) {
if t.Present && !t.Null {
return t.Val, nil
}
return nil, nil
}
func (t Time) MarshalJSON() ([]byte, error) {
if t.Present && !t.Null {
return json.Marshal(t.Val)
}
return nullString, nil
}