12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package hook
- import (
- "database/sql/driver"
- "encoding/json"
- "fmt"
- "time"
- "gorm.io/gorm"
- )
- const (
- LocalDateTimeFormat string = "2006-01-02 15:04:05"
- )
- type LocalTime time.Time
- // Scan 实现了 LocalTime 的 Scanner
- func (l *LocalTime) Scan(v interface{}) error {
- value, ok := v.(time.Time)
- if ok {
- *l = LocalTime(value)
- return nil
- }
- return fmt.Errorf("cannot convert %v to timestamp", v)
- }
- // Value 实现了 LocalTime 的 driver.Valuer
- func (l LocalTime) Value() (driver.Value, error) {
- if l.IsZero() {
- return nil, nil // Handle zero value case
- }
- return time.Time(l).Format(LocalDateTimeFormat), nil
- }
- // MarshalText 实现了 LocalTime 的 MarshalText
- func (l LocalTime) MarshalText() (text []byte, err error) {
- b := make([]byte, 0, len(LocalDateTimeFormat))
- b = time.Time(l).AppendFormat(b, LocalDateTimeFormat)
- if string(b) == `0001-01-01 00:00:00` {
- b = []byte(``)
- }
- return b, nil
- }
- // IsZero 实现了 LocalTime 的 IsZero
- func (l LocalTime) IsZero() bool {
- return time.Time(l).IsZero()
- }
- // UnmarshalJSON 实现了 LocalTime 的 UnmarshalJSON
- type DeletedAtWrapper struct {
- *gorm.DeletedAt
- }
- // "2006-01-02 15:04:05"
- func (d *DeletedAtWrapper) MarshalJSON() ([]byte, error) {
- if d == nil {
- return []byte("null"), nil
- }
- return json.Marshal(d.Time.Format(LocalDateTimeFormat))
- }
- func (t *LocalTime) UnmarshalJSON(data []byte) error {
- var expireTimeStr string
- err := json.Unmarshal(data, &expireTimeStr)
- if err != nil {
- return err
- }
- expireTime, err := time.Parse("2006-01-02 15:04:05", expireTimeStr)
- if err != nil {
- return err
- }
- *t = LocalTime(expireTime)
- return nil
- }
|