Skip to content

Instantly share code, notes, and snippets.

@ukkii
Created November 5, 2016 07:57
Show Gist options
  • Select an option

  • Save ukkii/31d51fc617c43332bd92281ed7a77cb0 to your computer and use it in GitHub Desktop.

Select an option

Save ukkii/31d51fc617c43332bd92281ed7a77cb0 to your computer and use it in GitHub Desktop.
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