From d115e1c5baba1506165462b23bdf595c7a3395a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Wed, 27 Nov 2024 11:26:37 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0gjson=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E6=95=B0=E5=AD=97=E7=B1=BB=E5=9E=8B=E8=BD=AC=E6=8D=A2=E7=9A=84?= =?UTF-8?q?hack?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gjson_hack/README.md | 3 ++ gjson_hack/precision.go | 71 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 gjson_hack/README.md create mode 100644 gjson_hack/precision.go 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 +}