Created
November 5, 2016 07:57
-
-
Save ukkii/31d51fc617c43332bd92281ed7a77cb0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package models | |
| import ( | |
| "time" | |
| "encoding/json" | |
| ) | |
| type NullTime struct { | |
| Time time.Time | |
| Valid bool | |
| } | |
| func (nt *NullTime) Scan(value interface{}) error { | |
| nt.Time, nt.Valid = value.(time.Time) | |
| return nil | |
| } | |
| func (nt NullTime) GetBSON() (interface{}, error) { | |
| if !nt.Valid { | |
| return nil, nil | |
| } | |
| return nt.Time, nil | |
| } | |
| func (nt NullTime) MarshalJSON() ([]byte, error) { | |
| if !nt.Valid { | |
| return []byte("null"), nil | |
| } | |
| return json.Marshal(nt.Time) | |
| } | |
| func (nt *NullTime) UnmarshalJSON(b []byte) error { | |
| if b[0] == '"' && b[len(b)-1] == '"' { | |
| b = b[1 : len(b)-1] | |
| } | |
| if string(b[:]) == "null" { | |
| *nt = NullTime{} | |
| return nil | |
| } | |
| nt.Valid = true | |
| nt.Time, _ = time.Parse(time.RFC3339, string(b)) | |
| return nil | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment