feat(gormtypes): go-hua/datatypes 迁入并更名 gormtypes(GORM/JSON 双向类型)

- 原包名与 gorm.io/datatypes 易混淆, 实为 GORM Value/Scanner + JSON 序列化
  类型族, 更名 gormtypes; 8 种类型与测试同步迁移
- 附 examples/gormtypes 例程与包 README
This commit is contained in:
2026-09-20 12:37:10 +08:00
parent 63d0a0caf8
commit 424877d3ac
18 changed files with 3092 additions and 0 deletions
+70
View File
@@ -0,0 +1,70 @@
// gormtypes 包示例:GORM/JSON 双向转换类型。
// 同一类型既能在 GORM 层序列化为 JSON 存库(Value/Scan),
// 又能在 API 层按前端需要的格式输出(MarshalJSON/UnmarshalJSON)。
package main
import (
"encoding/json"
"fmt"
"git.zeroonesoft.cn/golib/zogo/gormtypes"
)
// Model 模拟 GORM 模型
type Model struct {
Tags gormtypes.StringSlice `json:"tags"`
Nums gormtypes.IntSlice `json:"nums"`
Flags gormtypes.BoolSlice `json:"flags"`
Extra gormtypes.StringMap `json:"extra"`
}
func main() {
// ===== StringSlice =====
s := gormtypes.StringSlice{"a", "b", "c"}
fmt.Println("Contains b:", s.Contains("b"))
fmt.Println("Join:", s.Join(","))
fmt.Println("ToSlice:", s.ToSlice())
buf, _ := json.Marshal(s)
fmt.Println("MarshalJSON:", string(buf))
// Value/Scan:GORM 写库/读库时调用,nil 统一转 []
v, _ := s.Value()
fmt.Printf("Value: %s\n", v)
var s2 gormtypes.StringSlice
_ = s2.Scan(v)
fmt.Println("Scan 后:", s2)
// ===== IntSlice:MarshalJSON 输出字符串数组(避免前端 JS 大数精度丢失)=====
nums := gormtypes.IntSlice{1, 2, 3}
buf, _ = json.Marshal(nums)
fmt.Println("IntSlice MarshalJSON:", string(buf))
var nums2 gormtypes.IntSlice
// 反序列化同时兼容字符串数组和数字数组
_ = json.Unmarshal([]byte(`["1","2","3"]`), &nums2)
fmt.Println("IntSlice UnmarshalJSON(字符串数组):", nums2)
_ = json.Unmarshal([]byte(`[4,5]`), &nums2)
fmt.Println("IntSlice UnmarshalJSON(数字数组):", nums2)
// ===== StringMap =====
m := gormtypes.StringMap{}
m.Set("k1", "v1")
m.Set("k2", "v2")
fmt.Println("Get k1:", m.Get("k1"))
fmt.Println("Keys:", m.Keys())
fmt.Println("Values:", m.Values())
buf, _ = json.Marshal(m)
fmt.Println("StringMap MarshalJSON:", string(buf))
// ===== BoolSlice =====
flags := gormtypes.BoolSlice{true, false, true}
fmt.Println("AnyTrue:", flags.AnyTrue(), "AllTrue:", flags.AllTrue(), "CountTrue:", flags.CountTrue())
// ===== 完整模型 JSON 序列化 =====
mo := Model{Tags: s, Nums: nums, Flags: flags, Extra: m}
buf, _ = json.Marshal(mo)
fmt.Println("Model JSON:", string(buf))
// ===== 从 JSON 反序列化(等价于从数据库 JSON 字符串 Scan)=====
_ = json.Unmarshal([]byte(`{"tags":["x"],"nums":["9"],"flags":[true],"extra":{"a":"b"}}`), &mo)
fmt.Printf("Unmarshal 后: %+v\n", mo)
}