zhangqian
2023-12-08 84fb8e390b83dc9482524c12d7af6c93405c3fc1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package model
 
import (
    "apsClient/pkg/snowflake"
    "encoding/json"
    "github.com/jinzhu/gorm"
    "strconv"
    "time"
)
 
type CommonModel struct {
    ID        uint   `gorm:"primary_key;autoIncrement:false" json:"-"`
    IDStr     string `json:"ID" gorm:"-"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}
 
func (c *CommonModel) BeforeCreate(db *gorm.DB) {
    if c.ID == 0 {
        id := snowflake.GenerateID()
        if id < 0 {
            id = snowflake.GenerateID()
        }
        c.ID = uint(id)
    }
}
func (c CommonModel) UnmarshalJSON(b []byte) (err error) {
    id, err := strconv.ParseUint(c.IDStr, 10, 64)
    if err != nil {
        return err
    }
    c.ID = uint(id)
    return
}
 
func (c CommonModel) MarshalJSON() ([]byte, error) {
    c.IDStr = strconv.FormatUint(uint64(c.ID), 10)
    return json.Marshal(c)
}