package entity import ( "database/sql/driver" "fmt" "github.com/google/uuid" "gorm.io/gorm" "strings" "time" ) type Base struct { Id string `json:"id" gorm:"primaryKey;type:varchar(36);not null;comment:'主键'"` Timestamp } func (b *Base) BeforeCreate(*gorm.DB) (err error) { if b.Id == "" { b.Id = strings.ReplaceAll(uuid.NewString(), "-", "") } return } type JsonTime struct { time.Time } type Timestamp struct { CreatedAt JsonTime UpdatedAt JsonTime } func (jt JsonTime) MarshalJSON() ([]byte, error) { if jt.IsZero() { return []byte(`""`), nil } output := fmt.Sprintf("\"%s\"", jt.Format("2006-01-02 15:04:05")) return []byte(output), nil } func (jt JsonTime) Value() (driver.Value, error) { var zeroTime time.Time if jt.Time.UnixNano() == zeroTime.UnixNano() { return nil, nil } return jt.Time.Format("2006-01-02 15:04:05"), nil } func (jt *JsonTime) Scan(v interface{}) error { value, ok := v.(time.Time) if ok { *jt = JsonTime{Time: value} return nil } return fmt.Errorf("can not convert %v to timestamp", v) }