自定义一个类型实现go时间类型的json和bson的序列化和反序列化
需求
go语言在时间 和 json 转换时使用 yyyy-MM-dd HH:mm:ss 的格式,存到mongo时使用 时间戳(秒) 保存
实现 -自定义JSONTime类型
package JSONTime
import (
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"time"
)
const (
YYYYMMDD = "2006-01-02"
DefaultTimeFormat = "2006-01-02 15:04:05"
)
// 自定义 类型
type JSONTime struct {
Time time.Time
}
//实现 json 的反序列方法
func (t *JSONTime) UnmarshalJSON(data []byte) (err error) {
now, err := time.ParseInLocation(`"`+DefaultTimeFormat+`"`, string(data), time.Local)
t.Time = now
return
}
// 实现 json 的序列化方法
func (t JSONTime) MarshalJSON() ([]byte, error) {
b := make([]byte, 0, len(DefaultTimeFormat)+2)
b = append(b, '"')
b = t.Time.AppendFormat(b, DefaultTimeFormat)
b = append(b, '"')
return b, nil
}
//初始化时间戳 2006-01-02 15:04:01
const INIT_TIMESTAMPT = 1136185440
//实现 bson 的 序列化方法
func (t *JSONTime) MarshalBSONValue() (bsontype.Type, []byte, error) {
timestampt := t.Time.Unix()
if timestampt < 0 {
timestampt = INIT_TIMESTAMPT
}
retByte := make([]byte, 0)
retByte = bsoncore.AppendInt64(retByte, timestampt)
return bsontype.Int64, retByte, nil
}
//实现 bson 的 反序列化方法
func (t *JSONTime) UnmarshalBSONValue(ty bsontype.Type, data []byte) error {
if ty == bsontype.Int64 {
if readInt64, _, ok := bsoncore.ReadInt64(data); ok {
t.Time = time.Unix(readInt64, 0)
}
}
return nil
}
如何使用?
type User struct {
......
CreatedAt JSONTime.JSONTime `json:"created_at" bson:"created_at"`
......
}