68 lines
1.2 KiB
Go
68 lines
1.2 KiB
Go
package model
|
|
|
|
import (
|
|
"database/sql/driver"
|
|
"fmt"
|
|
"github.com/google/uuid"
|
|
"gorm.io/gorm"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Base
|
|
// @description: 数据模型基类
|
|
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 any) error {
|
|
value, ok := v.(time.Time)
|
|
if ok {
|
|
*jt = JsonTime{Time: value}
|
|
return nil
|
|
}
|
|
return fmt.Errorf("can not convert %v to timestamp", v)
|
|
}
|
|
|
|
func (jt JsonTime) String() string {
|
|
if jt.IsZero() {
|
|
return ""
|
|
}
|
|
output := fmt.Sprintf("%s", jt.Format("2006-01-02 15:04:05"))
|
|
return output
|
|
}
|