zhangqian
2023-12-08 c68a2d376f67d60277001e3f748fbd71c5201af3
debug
1个文件已修改
33 ■■■■■ 已修改文件
model/model.go 33 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
model/model.go
@@ -8,9 +8,10 @@
    "time"
)
type BigID uint
type CommonModel struct {
    ID        uint   `gorm:"primary_key" json:"-"`
    IDStr     string `json:"ID" gorm:"-"`
    ID        BigID `gorm:"primary_key"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
@@ -23,32 +24,26 @@
            // 处理 ID 为负数的情况(可选)
            id = snowflake.GenerateID()
        }
        c.ID = uint(id)
        c.ID = BigID(id)
    }
}
func (c *CommonModel) UnmarshalJSON(b []byte) error {
    var data map[string]interface{}
    if err := json.Unmarshal(b, &data); err != nil {
func (id *BigID) UnmarshalJSON(b []byte) error {
    var idString string
    if err := json.Unmarshal(b, &idString); err != nil {
        return err
    }
    if idStr, ok := data["ID"].(string); ok {
        id, err := strconv.ParseUint(idStr, 10, 64)
        if err != nil {
            return err
        }
        c.ID = uint(id)
        c.IDStr = idStr
    idValue, err := strconv.ParseUint(idString, 10, 64)
    if err != nil {
        return err
    }
    *id = BigID(idValue)
    return nil
}
func (c *CommonModel) MarshalJSON() ([]byte, error) {
    if c.ID != 0 && c.IDStr == "" {
        c.IDStr = strconv.FormatUint(uint64(c.ID), 10)
    }
    return json.Marshal(c)
func (id *BigID) MarshalJSON() ([]byte, error) {
    idString := strconv.FormatUint(uint64(*id), 10)
    return []byte(idString), nil
}