wireguard-dashboard/model/entity/base.go

66 lines
1.2 KiB
Go
Raw Permalink Normal View History

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