// JSON marshals to the zero value for time.Time if null.
// Considered to be null to SQL if zero.
typeTimestruct{
Timetime.Time
Validbool
}
// Scan implements Scanner interface.
func(t*Time)Scan(valueinterface{})error{
varerrerror
switchx:=value.(type){
casetime.Time:
t.Time=x
casenil:
t.Valid=false
returnnil
default:
err=fmt.Errorf("null: cannot scan type %T into null.Time: %v",value,value)
}
t.Valid=err==nil
returnerr
}
// Value implements the driver Valuer interface.
func(tTime)Value()(driver.Value,error){
if!t.Valid{
returnnil,nil
}
returnt.Time,nil
}
// NewTime creates a new Time.
funcNewTime(ttime.Time,validbool)Time{
returnTime{
Time:t,
Valid:valid,
}
}
// TimeFrom creates a new Time that will
// be null if t is the zero value.
funcTimeFrom(ttime.Time)Time{
returnNewTime(t,!t.IsZero())
}
// TimeFromPtr creates a new Time that will
// be null if t is nil or *t is the zero value.
funcTimeFromPtr(t*time.Time)Time{
ift==nil{
returnNewTime(time.Time{},false)
}
returnTimeFrom(*t)
}
// MarshalJSON implements json.Marshaler.
// It will encode the zero value of time.Time
// if this time is invalid.
func(tTime)MarshalJSON()([]byte,error){
if!t.Valid{
return(time.Time{}).MarshalJSON()
}
returnt.Time.MarshalJSON()
}
// UnmarshalJSON implements json.Unmarshaler.
// It supports string, object (e.g. pq.NullTime and friends)
// and null input.
func(t*Time)UnmarshalJSON(data[]byte)error{
varerrerror
varvinterface{}
iferr=json.Unmarshal(data,&v);err!=nil{
returnerr
}
switchx:=v.(type){
casestring:
vartitime.Time
iferr=ti.UnmarshalJSON(data);err!=nil{
returnerr
}
*t=TimeFrom(ti)
returnnil
casemap[string]interface{}:
ti,tiOK:=x["Time"].(string)
valid,validOK:=x["Valid"].(bool)
if!tiOK||!validOK{
returnfmt.Errorf(`json: unmarshalling object into Go value of type null.Time requires key "Time" to be of type string and key "Valid" to be of type bool; found %T and %T, respectively`,x["Time"],x["Valid"])
}
err=t.Time.UnmarshalText([]byte(ti))
t.Valid=valid
returnerr
casenil:
t.Valid=false
returnnil
default:
returnfmt.Errorf("json: cannot unmarshal %v into Go value of type null.Time",reflect.TypeOf(v).Name())