diff --git a/gjson_hack/README.md b/gjson_hack/README.md new file mode 100644 index 0000000..80f9933 --- /dev/null +++ b/gjson_hack/README.md @@ -0,0 +1,3 @@ +# 对gjson库一些已知问题的pack + +- 大数字 res.Int() 缺失精度 \ No newline at end of file diff --git a/gjson_hack/precision.go b/gjson_hack/precision.go new file mode 100644 index 0000000..0c65e03 --- /dev/null +++ b/gjson_hack/precision.go @@ -0,0 +1,71 @@ +// Package gjson_hack ... +// +// Description : gjson_hack ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2024-11-27 10:47 +package gjson_hack + +import ( + "errors" + "git.zhangdeman.cn/zhangdeman/util" + "github.com/tidwall/gjson" +) + +// Number 结果转换为数字(int64 / uint64 / float64) +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 10:57 2024/11/27 +func Number[T int64 | uint64 | float64](gjsonResult gjson.Result, numberReceiver *T) error { + if !gjsonResult.Exists() { + return errors.New("gjson result not found") + } + if gjsonResult.Type != gjson.Number { + return errors.New(gjsonResult.String() + " : value not a number") + } + if err := util.ConvertAssign(numberReceiver, gjsonResult.String()); nil != err { + return errors.New(gjsonResult.String() + " : convert to num fail -> " + err.Error()) + } + return nil +} + +// Int 转int +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 11:19 2024/11/27 +func Int(gjsonResult gjson.Result) (int64, error) { + var intResult int64 + if err := Number(gjsonResult, &intResult); nil != err { + return 0, err + } + return intResult, nil +} + +// Uint 转为uint64 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 11:21 2024/11/27 +func Uint(gjsonResult gjson.Result) (uint64, error) { + var uintResult uint64 + if err := Number(gjsonResult, &uintResult); nil != err { + return 0, err + } + return uintResult, nil +} + +// Float64 转为float64 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 11:24 2024/11/27 +func Float64(gjsonResult gjson.Result) (float64, error) { + var float64Result float64 + if err := Number(gjsonResult, &float64Result); nil != err { + return 0, err + } + return float64Result, nil +}