Documentation
¶
Overview ¶
* @Author: kamalyes 501893067@qq.com * @Date: 2025-11-16 22:55:55 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2025-11-16 22:55:55 * @FilePath: \go-toolbox\pkg\safe\mathx.go * @Description: 安全的数学工具函数集合,提供各种数学算法的安全实现 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
* @Author: kamalyes 501893067@qq.com * @Date: 2025-02-28 00:00:00 * @LastEditors: kamalyes 501893067@qq.com * @LastEditTime: 2026-05-13 22:56:07 * @FilePath: \go-toolbox\pkg\safe\struct_tags.go * @Description: 结构体 tag 解析与字段别名归一化 * * Copyright (c) 2025 by kamalyes, All Rights Reserved.
Index ¶
- Constants
- Variables
- func Abs(n int64) (int64, error)
- func Add(a, b int64) (int64, error)
- func AddStringFieldAlias(aliases map[string]struct{}, name string)
- func As[T types.Numerical](s *Access, defaultValue ...T) T
- func AsFloat[T types.Float](s *Access, mode convert.RoundMode, defaultValue ...T) T
- func AsFloatSlice[T types.Float](s *Access, mode convert.RoundMode) ([]T, error)
- func AsSlice[T types.Numerical](s *Access) ([]T, error)
- func Average(numbers []int64) (float64, error)
- func BoolPtr(src *bool) bool
- func BytesPtr(src *[]byte) []byte
- func Clamp(value, min, max int64) (int64, error)
- func Divide(a, b int64) (int64, error)
- func DurationPtr(src *time.Duration) time.Duration
- func ExtractGormColumnName(field reflect.StructField) string
- func ExtractGormType(field reflect.StructField) string
- func ExtractStructuredTagValue(tag string, key string) string
- func Factorial(n int) (*big.Int, error)
- func FastHash(s string) uint64
- func Fibonacci(n int) (int64, error)
- func FieldNameAliases(name string) []string
- func Float32Ptr(src *float32) float32
- func Float64Ptr(src *float64) float64
- func GCD(a, b int64) int64
- func GenericStructType[T any]() reflect.Type
- func GetBool(m map[string]interface{}, key string) bool
- func GetString(m map[string]interface{}, key string) string
- func GetStringSlice(m map[string]interface{}, key string) []string
- func HashToInt64(parts []string, separator string) int64
- func Int32Ptr(src *int32) int32
- func Int64Ptr(src *int64) int64
- func IntPtr(src *int) int
- func IsPrime(n int64) bool
- func IsType[T any](s *Access) bool
- func LCM(a, b int64) (int64, error)
- func Log(n, base float64) (float64, error)
- func Max(numbers []int64) (int64, error)
- func MergeWithDefaults[T any](st *T, defaultSts ...*T) *T
- func Min(numbers []int64) (int64, error)
- func Modulo(a, b int64) (int64, error)
- func Multiply(a, b int64) (int64, error)
- func Must[T any](s *Access) T
- func NextPowerOfTwo(n int) int
- func NormalizeStringFieldMapByTagType[T any](fields map[string]interface{}, tagName string, typeMatches func(string) bool, ...)
- func NormalizeStringFieldsByTagType(target interface{}, tagName string, typeMatches func(string) bool, ...)
- func OrDefault[T any](s *Access, defaultValue T) T
- func Power(base, exp int64) (int64, error)
- func Ptr[T any, R any](src *T, f func(T) R) *R
- func ShortHash(s string) string
- func ShortHashWithLength(s string, length int) string
- func SlicePtr[T any](src *[]T) []T
- func Sqrt(n float64) (float64, error)
- func StringFieldAliasesByTagType[T any](tagName string, typeMatches func(string) bool) map[string]struct{}
- func StringPtr(src *string) string
- func Subtract(a, b int64) (int64, error)
- func UintPtr(src *uint) uint
- type Access
- func (s *Access) AsBool() bool
- func (s *Access) AsJSON(indent bool) (string, error)
- func (s *Access) AsString(timeLayout ...string) string
- func (s *Access) AsStringSlice() []string
- func (s *Access) At(fieldPath string, defaultValue ...interface{}) *Access
- func (s *Access) Bool(defaultValue ...bool) bool
- func (s *Access) BoolAt(fieldPath string, defaultValue ...bool) bool
- func (s *Access) Contains(target interface{}) bool
- func (s *Access) Duration(defaultValue ...time.Duration) time.Duration
- func (s *Access) DurationAt(fieldPath string, defaultValue ...time.Duration) time.Duration
- func (s *Access) Field(fieldName string) *Access
- func (s *Access) Filter(predicate func(interface{}) bool) *Access
- func (s *Access) FlatMap(fn func(interface{}) *Access) *Access
- func (s *Access) Float32(defaultValue ...float32) float32
- func (s *Access) Float64(defaultValue ...float64) float64
- func (sa *Access) GetInt64Value(defaultValue int64) int64
- func (sa *Access) GetIntValue(defaultValue int) int
- func (s *Access) IfPresent(fn func(interface{})) *Access
- func (s *Access) Int(defaultValue ...int) int
- func (s *Access) Int32(defaultValue ...int32) int32
- func (s *Access) Int64(defaultValue ...int64) int64
- func (s *Access) IntAt(fieldPath string, defaultValue ...int) int
- func (s *Access) IsBool() bool
- func (s *Access) IsEmpty() bool
- func (s *Access) IsMap() bool
- func (s *Access) IsNonEmpty() bool
- func (s *Access) IsNumber() bool
- func (s *Access) IsSlice() bool
- func (s *Access) IsString() bool
- func (s *Access) IsValid() bool
- func (s *Access) Keys() []string
- func (s *Access) Len() int
- func (s *Access) Map(fn func(interface{}) interface{}) *Access
- func (s *Access) OrElse(alternative interface{}) *Access
- func (s *Access) String(defaultValue ...string) string
- func (s *Access) StringAt(fieldPath string, defaultValue ...string) string
- func (s *Access) StringOr(defaultValue string) string
- func (s *Access) StringOrAt(fieldPath string, defaultValue string) string
- func (s *Access) Uint(defaultValue ...uint) uint
- func (s *Access) Uint64(defaultValue ...uint64) uint64
- func (s *Access) Unless(predicate func(interface{}) bool, fn func(interface{}) interface{}) *Access
- func (s *Access) Value() interface{}
- func (s *Access) ValueAt(fieldPath string, defaultValue ...interface{}) interface{}
- func (s *Access) Values() []interface{}
- func (s *Access) When(predicate func(interface{}) bool, fn func(interface{}) interface{}) *Access
- type KV
- type NilPanicDetector
- type NilPanicIssue
- type RiskPattern
- type TemporalHasher
- func (h *TemporalHasher) Hash(parts ...string) string
- func (h *TemporalHasher) HashAt(t time.Time, parts ...string) string
- func (h *TemporalHasher) HashMap(kvMap map[string]string) string
- func (h *TemporalHasher) HashMapAt(t time.Time, kvMap map[string]string) string
- func (h *TemporalHasher) IsExpired(hash string, parts ...string) bool
- func (h *TemporalHasher) IsExpiredMap(hash string, kvMap map[string]string) bool
- func (h *TemporalHasher) Length() int
- func (h *TemporalHasher) Window() time.Duration
- type TemporalHasherOption
Constants ¶
const ( // 使用int64避免32位架构溢出 MaxSafeInteger64 = int64(1<<53 - 1) // JavaScript安全整数最大值 MinSafeInteger64 = int64(-(1<<53 - 1)) // JavaScript安全整数最小值 GoldenRatio = 1.618033988749 // 黄金比例 EulerNumber = 2.718281828459 // 欧拉数 )
定义常用的数学常数
Variables ¶
var ( MaxSafeInteger = getMaxSafeIntegerForArch() MinSafeInteger = getMinSafeIntegerForArch() )
架构相关的安全整数最大值
Functions ¶
func AddStringFieldAlias ¶
AddStringFieldAlias 向别名集合中添加字符串字段别名 忽略空字符串和 "-"(表示字段被忽略)
func AsFloatSlice ¶
AsFloatSlice 泛型浮点数切片转换
func DurationPtr ¶
DurationPtr 安全转换 *time.Duration 到 time.Duration(默认0)
func ExtractGormColumnName ¶
func ExtractGormColumnName(field reflect.StructField) string
ExtractGormColumnName 从 gorm 结构体标签中提取列名
func ExtractGormType ¶
func ExtractGormType(field reflect.StructField) string
ExtractGormType 从 gorm 结构体标签中提取数据库类型
func ExtractStructuredTagValue ¶
ExtractStructuredTagValue 从分号分隔的结构化标签中提取值 例如从 `gorm:"column:detail;type:json"` 中提取 column 或 type 的值
func FieldNameAliases ¶
FieldNameAliases 返回字段名的别名列表 包含原始字段名和 snake_case 形式(如果两者不同)
func GenericStructType ¶
GenericStructType 获取泛型结构体的反射类型 自动解引用指针类型,返回最终的结构体类型
func GetStringSlice ¶
GetStringSlice 安全获取map中的字符串切片
func HashToInt64 ¶
HashToInt64 将多个字符串拼接后哈希为非负 int64 内部使用 FNV-1a 短哈希 + Base36 解码,保证确定性且跨平台一致
参数:
- parts: 待哈希的字符串切片
- separator: 拼接分隔符
返回:非负的 int64 哈希值
func MergeWithDefaults ¶
func MergeWithDefaults[T any](st *T, defaultSts ...*T) *T
MergeWithDefaults 合并配置,用默认配置填充nil或零值字段 支持泛型,会递归合并所有嵌套结构体、指针、切片、Map等
func NormalizeStringFieldMapByTagType ¶
func NormalizeStringFieldMapByTagType[T any](fields map[string]interface{}, tagName string, typeMatches func(string) bool, normalize func(string) string)
NormalizeStringFieldMapByTagType 规范化 map 中的值 仅对键匹配带标签字符串字段别名的条目进行规范化
func NormalizeStringFieldsByTagType ¶
func NormalizeStringFieldsByTagType(target interface{}, tagName string, typeMatches func(string) bool, normalize func(string) string)
NormalizeStringFieldsByTagType 规范化结构体上的字符串字段 仅当配置的标签类型匹配提供的谓词函数时才进行规范化
func ShortHash ¶
ShortHash 生成短哈希字符串(默认7位,类似Git) 使用 FNV-1a 算法,适用于生成短ID、节点ID等场景 返回格式:7位Base36字符串(0-9a-z),如 "a1b2c3d" 冲突概率:10万节点 < 0.007%
func ShortHashWithLength ¶
ShortHashWithLength 生成指定长度的短哈希字符串 使用 FNV-1a 算法 + Base36 编码(0-9a-z)
参数:
- s: 输入字符串
- length: 哈希长度(最小为1),推荐值:
- 6位: 适合小规模(< 1万节点),冲突概率 < 0.002%
- 7位: 适合中规模(< 10万节点),冲突概率 < 0.007%(推荐)
- 8位: 适合大规模(< 100万节点),冲突概率 < 0.0002%
- 12-16位: 适合超大规模或需要更低冲突概率的场景
返回:指定长度的Base36字符串
示例:
ShortHashWithLength("192.168.1.100:8080", 7) → "3g5e9ss"
ShortHashWithLength("pod-abc-123", 8) → "2k3m4n5p"
ShortHashWithLength("user123", 16) → "3g5e9ss000000000"
Types ¶
type Access ¶
type Access struct {
// contains filtered or unexported fields
}
Access 安全访问装饰器
包住一个任意值,之后的取字段、转类型、取下标都不会 panic:路径不存在或类型 不符时返回零值或调用方给的默认值,而不是崩掉本包的「安全」指的就是这件事—— 程序不崩,与信息安全无关
命名不带 Safe 前缀
包名已经是 safe,再叫 SafeAccess 从包外看就是 safe.SafeAccess,重复一遍 Go 官方的命名约定正是为此:包名承担限定作用,类型名不该再重复它 同理 safe.Add / safe.Sqrt / safe.GetString 而不是 safe.SafeAdd 等, 入口从 safe.Safe(v) 改为 safe.New(v)——原先那个函数的文档注释本来就写着 New
[EN] A wrapper around an arbitrary value: field access, type conversion and indexing on it never panic, returning a zero value or a caller-supplied default when the path is missing or the type does not match. "Safe" here means exactly that — the program does not crash — and has nothing to do with information security.
The name carries no Safe prefix. The package is already called safe, so SafeAccess reads as safe.SafeAccess from outside and says it twice; Go's naming convention exists for this, with the package name doing the qualifying. Likewise safe.Add, safe.Sqrt and safe.GetString rather than safe.SafeAdd, and the entry point is safe.New(v) rather than safe.Safe(v) — whose own doc comment already said New
func New ¶
func New(v interface{}) *Access
New 创建安全访问装饰器
v 为 nil 时返回的 Access 标记为无效,后续取值一律走默认值分支
[EN] Creates the decorator. A nil v yields an Access marked invalid, so every later read takes the default-value path
func (*Access) DurationAt ¶
DurationAt 获取时间间隔字段的便捷方法
func (*Access) Field ¶
Field 安全访问字段,支持链式调用 支持多种命名风格:camelCase, PascalCase, snake_case, kebab-case
先按调用方给的原名直取,未命中才去算命名风格变体: 原名命中是最常见的情形,而算变体要做四次字符串转换并各分配一次, 让命中路径免掉这笔开销比优化未命中路径划算得多
[EN] The caller's own spelling is tried first and the naming-style variants are only computed on a miss. Hitting on the given name is the common case, while building variants means four string conversions with an allocation each, so sparing the hit path that cost matters more than tuning the miss path
func (*Access) GetInt64Value ¶
GetInt64Value 从Access中获取int64值,支持int/int64/float64类型转换
func (*Access) GetIntValue ¶
GetIntValue 从Access中获取int值,支持int/int64/float64类型转换
func (*Access) StringOrAt ¶
StringOrAt 获取字符串字段,支持空值默认值
type KV ¶
type KV[K comparable, V any] map[K]V
type NilPanicDetector ¶
type NilPanicDetector struct {
// contains filtered or unexported fields
}
NilPanicDetector Nil Panic检测器
func (*NilPanicDetector) GenerateReport ¶
func (d *NilPanicDetector) GenerateReport() string
GenerateReport 生成报告
func (*NilPanicDetector) GetFixSuggestions ¶
func (d *NilPanicDetector) GetFixSuggestions() []string
GetFixSuggestions 获取修复建议
func (*NilPanicDetector) GetIssues ¶
func (d *NilPanicDetector) GetIssues() []NilPanicIssue
GetIssues 获取所有检测到的问题
func (*NilPanicDetector) ScanDirectory ¶
func (d *NilPanicDetector) ScanDirectory(dirPath string) error
ScanDirectory 扫描目录中的Go文件
func (*NilPanicDetector) ScanFile ¶
func (d *NilPanicDetector) ScanFile(filePath string) error
ScanFile 扫描单个文件
type NilPanicIssue ¶
type NilPanicIssue struct {
File string `json:"file"`
Line int `json:"line"`
Column int `json:"column"`
Type string `json:"type"`
Description string `json:"description"`
Severity string `json:"severity"`
Code string `json:"code"`
}
NilPanicIssue Nil Panic问题
type RiskPattern ¶
RiskPattern 风险模式
type TemporalHasher ¶
type TemporalHasher struct {
// contains filtered or unexported fields
}
TemporalHasher 临时哈希生成器 在时间窗口内,相同输入生成相同哈希;超过窗口后生成新哈希
使用场景: - WebSocket ClientID:同一用户+设备短期内复用连接标识 - 会话标识:短期内相同条件复用会话 - 防重放:基于时间窗口的请求去重 - 缓存键:短期内相同条件复用缓存
func NewTemporalHasher ¶
func NewTemporalHasher(opts ...TemporalHasherOption) *TemporalHasher
NewTemporalHasher 创建临时哈希生成器
func (*TemporalHasher) Hash ¶
func (h *TemporalHasher) Hash(parts ...string) string
Hash 生成临时哈希 parts: 参与哈希计算的各个部分(会自动排序以保证一致性)
func (*TemporalHasher) HashAt ¶
func (h *TemporalHasher) HashAt(t time.Time, parts ...string) string
HashAt 使用指定时间生成哈希
func (*TemporalHasher) HashMap ¶
func (h *TemporalHasher) HashMap(kvMap map[string]string) string
HashMap 使用 map 生成哈希(会自动排序 key)
func (*TemporalHasher) IsExpired ¶
func (h *TemporalHasher) IsExpired(hash string, parts ...string) bool
IsExpired 检查哈希是否已过期(超过时间窗口)
func (*TemporalHasher) IsExpiredMap ¶
func (h *TemporalHasher) IsExpiredMap(hash string, kvMap map[string]string) bool
IsExpiredMap 检查哈希是否已过期(使用 map 参数)
type TemporalHasherOption ¶
type TemporalHasherOption func(*temporalHasherConfig)
TemporalHasherOption 配置选项函数