-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnull_time.go
55 lines (49 loc) · 1 KB
/
null_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
package gosql
import (
"database/sql/driver"
"encoding/json"
"time"
)
// NullTime holds an time.Time value that might be null in the
// database.
type NullTime struct {
Time time.Time
Valid bool
}
// Scan implements the Scanner interface.
func (n *NullTime) Scan(value interface{}) error {
if value == nil {
n.Valid = false
return nil
}
n.Valid = true
n.Time = value.(time.Time)
return nil
}
// Value implements the driver Valuer interface.
func (n NullTime) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
return n.Time, nil
}
// MarshalJSON implements the Marshaler interface.
func (n NullTime) MarshalJSON() ([]byte, error) {
if n.Valid {
return json.Marshal(n.Time)
}
return json.Marshal(nil)
}
// UnmarshalJSON implements the Unmarshaler interface.
func (n *NullTime) UnmarshalJSON(data []byte) error {
var t *time.Time
if err := json.Unmarshal(data, &t); err != nil {
return err
}
if t != nil {
n.Time, n.Valid = *t, true
} else {
n.Valid = false
}
return nil
}