xorm 使用技巧

这篇博客介绍了如何在Golang中使用xorm库处理自定义时间类型。通过定义DateTime和NullTime结构体,实现了JSON序列化、反序列化以及与数据库交互的功能。示例代码详细展示了MarshalJSON、UnmarshalJSON、FromDB、ToDB等方法的实现,以及如何扫描和写入数据库值,确保时间数据的准确转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

xorm 使用技巧

自定义类型

type DateTime time.Time

func (d DateTime) MarshalJSON() ([]byte, error) {
    t := time.Time(d)
    if t.IsZero() {
        return []byte{'"', '"'}, nil
    }
    res := make([]byte, 0, len(timeFormat)+2)
    res = append(res, '"')
    res = t.AppendFormat(res, timeFormat)
    res = append(res, '"')
    return res, nil
}

func (d *DateTime) UnmarshalJSON(bytes []byte) error {
    timeStr := strings.Trim(string(bytes), `"`)
    dateTime, err := time.ParseInLocation(timeFormat, timeStr, time.Local)
    *d = DateTime(dateTime)
    return err
}

func (d *DateTime) FromDB(bytes []byte) error {
    dateTime, err := time.ParseInLocation(time.RFC3339Nano, string(bytes), time.Local)
    *d = DateTime(dateTime)
    return err
}

func (d DateTime) ToDB() ([]byte, error) {
    res := make([]byte, 0, len(timeFormat))
    return time.Time(d).AppendFormat(res, timeFormat), nil
}

type NullTime sql.NullTime

func (s NullTime) MarshalJSON() ([]byte, error) {
    if !s.Valid {
        return []byte("null"), nil
    }
    return []byte(`"` + s.StringValue("2006-01-02 15:04:05") + `"`), nil
}

func (s *NullTime) UnmarshalJSON(data []byte) error {
    t := sql.NullTime{}
    if err := json.Unmarshal(data, &t); err != nil {
        timeStr := strings.Trim(string(data), `"`)
        if len(timeStr) >= 20 {
            timeStr = timeStr[:10] + " " + timeStr[11:19]
        }
        if len(timeStr) < 11 {
            timeStr += " 00:00:00"
        }
        timeVal, err := time.Parse("2006-01-02 15:04:05", timeStr)
        if err != nil {
            return err
        }
        *s = NullTime{Time: val, Valid: true}
        return nil
    }
    *s = NullTime(t)
    return nil
}

func (s NullTime) String() string {
    return s.StringValue("2006-01-02 15:04:05")
}

// 读取数据库
func (s *NullTime) Scan(value interface{}) error {
    n := sql.NullTime{Time: s.Time}
    if err := n.Scan(value); err != nil {
        return err
    }
    *s = NullTime(n)
    return nil
}

// 写入数据库
func (s NullTime) Value() (driver.Value, error) {
    if !s.Valid {
        return nil, nil
    }
    return s.StringValue("2006-01-02 15:04:05"), nil
}

func (s NullTime) StringValue(layout string) string {
    return s.Time.Format(layout)
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值