Documentation
¶
Overview ¶
Package serializer 提供响应数据的递归序列化能力。
支持将结构体、切片、map、指针等嵌套数据转换为统一的 map/slice 结构, 并在此过程中按需格式化时间字段、加密 uint64 类型的 ID 字段。 通过最大深度限制与循环引用检测,避免自引用结构体或极深嵌套导致栈溢出。
Index ¶
- func Process(data interface{}, opts ...Option) interface{}
- func ProcessValue(key string, val interface{}, opts ...Option) interface{}
- type Option
- func WithEncryptID(fn func(uint64) string) Option
- func WithFormatTime(fn func(interface{}) (string, bool)) Option
- func WithIDField(fn func(string) bool) Option
- func WithLegacyMode(enabled bool) Option
- func WithMaxDepth(depth int) Option
- func WithSkipField(fn func(reflect.StructField) bool) Option
- func WithTimeField(fn func(string) bool) Option
- type Options
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Process ¶
func Process(data interface{}, opts ...Option) interface{}
Process 递归处理数据:统一格式化时间字段,并按需加密 uint64 类型的 ID 字段。 支持 map、slice、struct、指针、嵌套结构。
通过最大深度限制与循环引用检测,避免自引用结构体或极深嵌套导致栈溢出。 超出最大深度时返回原始数据,避免子树数据缺失。
参数:
- data: 待处理的数据
- opts: 可选的处理策略
返回值:
- 处理后的数据;若检测到循环引用,对应位置返回 nil 以打破循环。
func ProcessValue ¶
ProcessValue 根据字段名处理单个字段:优先格式化时间,再按需加密 ID。
参数:
- key: 字段名
- val: 字段值
- opts: 可选的处理策略
返回值:
- 处理后的字段值。
Types ¶
type Option ¶
type Option func(*Options)
Option 函数式选项类型。
func WithFormatTime ¶
WithFormatTime 注入时间值格式化函数。
func WithLegacyMode ¶
WithLegacyMode 注入旧版序列化模式。
开启后,结构体通过 json.Marshal/Unmarshal 转为 map(与原 CRUD 行为一致), 切片仅转换为 []interface{} 而不递归处理元素,map 保持原样返回。 该模式主要用于向后兼容,避免已上线项目因序列化逻辑变更而出现响应差异。
func WithSkipField ¶
func WithSkipField(fn func(reflect.StructField) bool) Option
WithSkipField 注入字段跳过判断函数。
type Options ¶
type Options struct {
// EncryptID 可选:对 uint64 ID 字段加密(如 iMe 注入 utils.EncryptID)
EncryptID func(uint64) string
// IsIDField 可选:判断某字段是否需加密(默认空,即不加密)
IsIDField func(string) bool
// IsTimeField 可选:判断某字段是否需格式化为北京时间(默认空,即不处理时间字段)
IsTimeField func(string) bool
// FormatTime 可选:将时间值格式化为北京时间字符串
FormatTime func(interface{}) (string, bool)
// SkipField 可选:判断某结构体字段是否跳过(如跳过匿名嵌入的 orm base model)
SkipField func(reflect.StructField) bool
// MaxDepth 可选:递归处理的最大深度,小于等于 0 时使用默认值 32
MaxDepth int
// LegacyMode 可选:使用旧版 json.Marshal/Unmarshal 路径处理结构体与切片,
// 保持与重构前一致的输出行为。
LegacyMode bool
}
Options 序列化处理可配置项。所有回调均为可选注入,业务策略由调用方提供。
Click to show internal directories.
Click to hide internal directories.