zhangqian
2023-12-08 0ac236432543589b51613919d37cc7b7c07b9bf3
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
41
42
43
44
45
46
47
48
49
50
package model
 
import (
    "apsClient/pkg/snowflake"
    "encoding/json"
    "github.com/jinzhu/gorm"
    "strconv"
    "time"
)
 
type BigID uint
 
type CommonModel struct {
    ID        uint  `gorm:"primary_key" json:"-"`
    Id        BigID `json:"ID"`
    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 为负数的情况(可选)
            id = snowflake.GenerateID()
        }
        c.ID = uint(id)
    }
}
 
func (id *BigID) UnmarshalJSON(b []byte) error {
    var idString string
    if err := json.Unmarshal(b, &idString); err != nil {
        return err
    }
 
    idValue, err := strconv.ParseUint(idString, 10, 64)
    if err != nil {
        return err
    }
 
    *id = BigID(idValue)
    return nil
}
 
func (id *BigID) MarshalJSON() ([]byte, error) {
    idString := strconv.FormatUint(uint64(*id), 10)
    return []byte(idString), nil
}