场景
数据库为mongodb,驱动为mgo。从库中取数据后以json格式返给调用者。
type MyStruct struct{Time time.Time}
Time的MarshalJSON实现是转化为RFC3339格式的时间,
若没有赋值,格式化后为0001-01-01T00:00:00Z, 对调用者极不友好
null
json:",omitempty"0值
time.Time*time.Time0001-01-01T00:00:00Z
姿势不优雅
json.Marshalernull
type CustomTime struct{time.Time}func (t CustomTime) MarshalJSON() ([]byte, error) {fmt.Println(t.String())if t.Time.IsZero() {return []byte("null"), nil}return t.Time.MarshalJSON()}
大功告成
其实并没有。经测试发现,没赋值的变成了null,有正常值的也变成了null
time.Time
解决:
bson.Getterbson.Setter
func (t CustomTime) GetBSON() (interface{}, error) {if t.Time.IsZero() {return nil, nil}return t.Time, nil}func (t *CustomTime) SetBSON(raw bson.Raw) error {var tm time.Timeif err := raw.Unmarshal(&tm); err != nil {return err}t.Time = tmreturn nil}