我遇到了同样的问题,最终为创建了一个自定义类型
time.Time
package genericfieldsimport ( "encoding/json" "time" "strings" "gopkg.in/mgo.v2/bson")// ANYTIME //// AnyTime accepts any time format for its unmarshaling //type AnyTime struct{ time.Time }func (t AnyTime) MarshalJSON() ([]byte, error) { return json.Marshal(t.Time)}func (t *AnyTime) UnmarshalJSON(b []byte) error { err := json.Unmarshal(b, &t.Time) if err != nil { //assume non tz time input bstr := strings.Trim(string(b), `"`) t.Time, err = time.Parse("2006-01-02T15:04:05", bstr) if err != nil { return err //TODO add more formats to try } } return nil}func (t AnyTime) GetBSON() (interface{}, error) { return t.Time, nil}func (t *AnyTime) SetBSON(raw bson.Raw) error { var tm time.Time err := raw.Unmarshal(&tm) if err != nil { return err } t.Time = tm.UTC() return nil}func (t AnyTime) ToTime() time.Time { return t.Time}
用法:
type MyStruct struct { StartedAt genericfields.AnyTime `json:"startedAt" bson:"startedAt"` ...}
您可能需要对输入进行
time.Parse一些调整。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)