-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
time.go
77 lines (66 loc) · 1.62 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
package nulls
import (
"database/sql/driver"
"encoding/json"
"time"
)
// Time replaces sql.NullTime with an implementation
// that supports proper JSON encoding/decoding.
type Time struct {
Time time.Time
Valid bool // Valid is true if Time is not NULL
}
// Interface implements the nullable interface. It returns nil if
// the Time is not valid, otherwise it returns the Time value.
func (ns Time) Interface() interface{} {
if !ns.Valid {
return nil
}
return ns.Time
}
// NewTime returns a new, properly instantiated
// Time object.
func NewTime(t time.Time) Time {
return Time{Time: t, Valid: true}
}
// Scan implements the Scanner interface.
func (ns *Time) Scan(value interface{}) error {
ns.Time, ns.Valid = value.(time.Time)
return nil
}
// Value implements the driver Valuer interface.
func (ns Time) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
return ns.Time, nil
}
// MarshalJSON marshals the underlying value to a
// proper JSON representation.
func (ns Time) MarshalJSON() ([]byte, error) {
if ns.Valid {
return json.Marshal(ns.Time)
}
return json.Marshal(nil)
}
// UnmarshalJSON will unmarshal a JSON value into
// the propert representation of that value.
func (ns *Time) UnmarshalJSON(text []byte) error {
ns.Valid = false
txt := string(text)
if txt == "null" || txt == "" {
return nil
}
t := time.Time{}
err := t.UnmarshalJSON(text)
if err == nil {
ns.Time = t
ns.Valid = true
}
return err
}
// UnmarshalText will unmarshal text value into
// the propert representation of that value.
func (ns *Time) UnmarshalText(text []byte) error {
return ns.UnmarshalJSON(text)
}