golang + huma 开发过程中,如果你有过前端开发的经验,可能知道最好将 bigint(int64)(比如雪花 id)序列化成字符串(因为 js 处理 bigint 需要额外的手段)

但是这个需求在 huma 中有点麻烦

TLDR

huma/issues/698#issuecomment-3294634741

详解

 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
type BigInt int64

func (b *BigInt) UnmarshalJSON(data []byte) error {
	s := strings.Trim(string(data), `"`)
	if s == "" {
		*b = 0
		return nil
	}
	n, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		return err
	}
	*b = BigInt(n)
	return nil
}

func (b BigInt) MarshalJSON() ([]byte, error) {
	return fmt.Appendf(nil, `"%d"`, b), nil
}

// Define schema to use wrapped type
func (o BigInt) Schema(r huma.Registry) *huma.Schema {
	return huma.SchemaFromType(r, reflect.TypeOf(""))
}

type wrapperBigInt struct {
	b *BigInt
}

// implement encoding.TextUnmarshaler interface
func (w *wrapperBigInt) UnmarshalText(text []byte) error {
	s := strings.Trim(string(text), `"`)
	if s == "" {
		*w.b = 0
		return nil
	}
	n, err := strconv.ParseInt(s, 10, 64)
	if err != nil {
		return err
	}
	*w.b = BigInt(n)
	return nil
}

func (o *BigInt) Receiver() reflect.Value {
	a := new(wrapperBigInt)
	a.b = o
	return reflect.ValueOf(a).Elem()
}
  1. 实现 json 序列化接口,使之在 json 序列化和反序列化中能正确表现为字符串
  2. 实现 huma 的 SchemaProvider​ 接口 Schema(r huma.Registry) *huma.Schema​,使该类型生成 openapi 文档时表现为 string
  3. 上面两步做完,就能正常序列化和反序列化出 json body 的参数,但是对于 query 和 path 参数不行,还需要继续
  4. 实现 huma 的 ParamWrapper​ 接口 Receiver() reflect.Value​ 使该类型在接收值时表现为一个 struct,来使该类型的解析走 encoding.TextUnmarshaler huma.go#L1560-L1565
  5. 配置 struct 同时将原始值的指针设置到一个字段上,实现 encoding.TextUnmarshaler 时将数字反序列化回原始值