增加gjson安全数字类型转换的hack
This commit is contained in:
parent
fd1f3367ed
commit
d115e1c5ba
3
gjson_hack/README.md
Normal file
3
gjson_hack/README.md
Normal file
@ -0,0 +1,3 @@
|
||||
# 对gjson库一些已知问题的pack
|
||||
|
||||
- 大数字 res.Int() 缺失精度
|
71
gjson_hack/precision.go
Normal file
71
gjson_hack/precision.go
Normal file
@ -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
|
||||
}
|
Loading…
Reference in New Issue
Block a user