-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathnull_time.go
60 lines (53 loc) · 1.13 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
56
57
58
59
60
package types
import (
"database/sql/driver"
"encoding/json"
"time"
)
// Implementation taken from
// https://github.com/lib/pq/blob/master/encode.go#L518-L538.
//
// It would be great to just import it from there, but you get duplicate driver
// exceptions
// A NullTime is a Time that may be null. It can be encoded or decoded from
// JSON or the database.
type NullTime struct {
Valid bool
Time time.Time
}
func (nt *NullTime) UnmarshalJSON(b []byte) error {
if string(b) == "null" {
nt.Valid = false
return nil
}
var t time.Time
err := json.Unmarshal(b, &t)
if err != nil {
return err
}
nt.Valid = true
nt.Time = t
return nil
}
func (nt NullTime) MarshalJSON() ([]byte, error) {
if !nt.Valid {
return []byte("null"), nil
}
b, err := json.Marshal(nt.Time)
if err != nil {
return []byte{}, err
}
return b, nil
}
// Scan implements the Scanner interface.
func (nt *NullTime) Scan(value interface{}) error {
nt.Time, nt.Valid = value.(time.Time)
return nil
}
// Value implements the driver Valuer interface.
func (nt NullTime) Value() (driver.Value, error) {
if !nt.Valid {
return nil, nil
}
return nt.Time, nil
}