51 Commits

Author SHA1 Message Date
1cbfbe9597 Merge pull request 'feature/upgrade_dynamic_struct' (#9) from feature/upgrade_dynamic_struct into master
Reviewed-on: #9
2025-03-21 18:27:12 +08:00
8de0d9b942 升级consts pkg 2025-03-21 18:26:46 +08:00
2c73b9c034 修复map数据key错误 + 获取map数据方法 2025-03-18 18:20:59 +08:00
beb8c74e8a update go mod 2025-03-18 16:44:03 +08:00
3167ea0f50 merge master 2025-03-18 16:43:43 +08:00
c1588abcb4 Merge pull request '优化数组字符串处理' (#8) from feature/fix_arr into master
Reviewed-on: #8
2025-03-02 21:34:17 +08:00
34c8cf04fa update go mod 2025-03-02 21:33:55 +08:00
d5622fe0ca 优化数组字符串处理 2025-03-02 21:33:16 +08:00
743acb53f2 优化动态结构体生成 2025-02-07 12:20:52 +08:00
981ff94388 动态结构体增加SetMapData方法 2025-01-24 18:51:16 +08:00
febf5a63ad 动态结构体增加自定义序列化方法 2025-01-24 18:48:24 +08:00
bbf5184314 update 2025-01-24 18:23:01 +08:00
c503187022 动态结构体支持赋值 2025-01-24 18:06:29 +08:00
c757e551a8 update go mod 2025-01-24 17:16:20 +08:00
7b56590b57 修复flot.ToString的BUg 2024-12-23 12:08:03 +08:00
2f87fe0cd9 fix data type 2024-11-25 14:59:49 +08:00
91423fb146 data type使用枚举类型 2024-11-25 14:25:26 +08:00
b435398a94 map增加GetFloat64方法 2024-11-21 15:25:08 +08:00
e2c6fb3e91 map增加获取int64值方法 2024-11-21 15:20:31 +08:00
59aeb88808 map 增加获取字符串结果方法 2024-11-21 15:16:30 +08:00
4196d342f7 fix 2024-11-21 15:11:50 +08:00
3bb36680ad fix 2024-11-21 15:07:08 +08:00
b7890f7fd0 fix 2024-11-21 14:28:15 +08:00
a56574ff65 change easymap -> map 2024-11-21 14:22:09 +08:00
ddeb444afb Merge pull request '增加自定义BigInt类型' (#7) from feature/support_bigint into master
Reviewed-on: #7
2024-11-19 16:41:59 +08:00
fc0aa6cd5a 增加自定义BigInt类型 2024-11-19 16:41:35 +08:00
cfdb588156 Merge pull request '支持Map类型的包装' (#6) from feature/support_map into master
Reviewed-on: #6
2024-11-19 16:31:04 +08:00
0d6d72b07e 增加Map MarshalJSON 方法 2024-11-19 15:39:37 +08:00
db7bf0817e 增加Map为Nil判断 2024-11-19 15:28:47 +08:00
e95ed61cfc Map提供Set方法 2024-11-19 15:20:25 +08:00
51d0a05ec3 map 增加Get与Filter方法 2024-11-19 15:12:48 +08:00
fcaa7ee1c2 增加map clone 2024-11-06 19:50:09 +08:00
5ea67a5b6c 完成map包装类型 - key是否存在 2024-11-06 18:40:49 +08:00
822aabaac6 update MapResult 2024-11-06 18:39:32 +08:00
dac3a32e6f easy map 2024-11-06 18:29:18 +08:00
118ef5d59a rename file : map.go -> easymap.go 2024-11-06 18:26:49 +08:00
46cd353dd6 update go mod 2024-11-06 18:25:17 +08:00
6dd5f7ac62 fix seriasize 2024-10-24 21:52:51 +08:00
e3de2835a9 优化提取字段返回值 2024-10-13 19:28:16 +08:00
f3f064d064 支持提取每一项Item的指定字段作为list返回 2024-10-13 19:23:20 +08:00
ef80c6cb79 修复anyType IsNil判断的BUG 2024-09-24 14:34:49 +08:00
c38d16dc28 动态结构体,字段可导出 2024-08-23 18:30:24 +08:00
59ba4ebfa5 Merge pull request '完成v1版本动态结构体创建' (#5) from feature/dynamic_struct into master
Reviewed-on: #5
2024-08-21 18:16:56 +08:00
18351f3b29 完成v1版本动态结构体创建 2024-08-21 18:16:21 +08:00
e4cef0855e 动态生成结构体的基础能力 2024-08-21 17:09:00 +08:00
da44ae07ab 优化IsNil判断 2024-08-13 16:30:16 +08:00
3533617196 update go mod 2024-08-06 15:23:20 +08:00
9ff1c213bb 计算字符串hash nimber 2024-06-27 11:17:06 +08:00
8d056baada Merge branch 'master' of git.zhangdeman.cn:zhangdeman/wrapper 2024-06-12 16:38:58 +08:00
ed0c57913a 完善any2string 2024-06-12 16:38:51 +08:00
588df729e0 变更 interface{} => any 2024-06-08 20:06:35 +08:00
20 changed files with 704 additions and 224 deletions

109
any.go
View File

@ -9,6 +9,7 @@ package wrapper
import ( import (
"fmt" "fmt"
"git.zhangdeman.cn/zhangdeman/consts"
"git.zhangdeman.cn/zhangdeman/serialize" "git.zhangdeman.cn/zhangdeman/serialize"
"reflect" "reflect"
) )
@ -18,7 +19,7 @@ import (
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 18:19 2023/6/1 // Date : 18:19 2023/6/1
func AnyDataType(data interface{}) *AnyType { func AnyDataType(data any) *AnyType {
at := &AnyType{ at := &AnyType{
data: data, data: data,
} }
@ -32,8 +33,8 @@ func AnyDataType(data interface{}) *AnyType {
// //
// Date : 18:19 2023/6/1 // Date : 18:19 2023/6/1
type AnyType struct { type AnyType struct {
data interface{} data any
dataType string dataType consts.DataType
} }
// IsNil 是否为 nil // IsNil 是否为 nil
@ -42,7 +43,18 @@ type AnyType struct {
// //
// Date : 18:21 2023/6/1 // Date : 18:21 2023/6/1
func (at *AnyType) IsNil() bool { func (at *AnyType) IsNil() bool {
return at.data == nil if at.data == nil {
return true
}
reflectValue := reflect.ValueOf(at.data)
switch reflectValue.Kind() {
case reflect.Chan, reflect.Func, reflect.Map,
reflect.Pointer, reflect.UnsafePointer,
reflect.Interface, reflect.Slice:
return reflectValue.IsNil()
default:
return false
}
} }
// Type 获取类型 // Type 获取类型
@ -50,34 +62,34 @@ func (at *AnyType) IsNil() bool {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 18:22 2023/6/1 // Date : 18:22 2023/6/1
func (at *AnyType) Type() string { func (at *AnyType) Type() consts.DataType {
if len(at.dataType) > 0 { if len(at.dataType) > 0 {
// 已经处理过的,无需在处理 // 已经处理过的,无需在处理
return at.dataType return at.dataType
} }
if at.IsNil() { if at.IsNil() {
return DataTypeNil return consts.DataTypeNil
} }
reflectType := reflect.TypeOf(at.data) reflectType := reflect.TypeOf(at.data)
switch reflectType.Kind() { switch reflectType.Kind() {
case reflect.String: case reflect.String:
return DataTypeString return consts.DataTypeString
case reflect.Slice, reflect.Array: case reflect.Slice, reflect.Array:
return DataTypeSlice return consts.DataTypeSliceAny
case reflect.Map, reflect.Struct: case reflect.Map, reflect.Struct:
return DataTypeObject return consts.DataTypeMapAnyAny
case reflect.Pointer: case reflect.Pointer:
return DataTypePtr return consts.DataTypePtr
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return DataTypeInt return consts.DataTypeInt
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return DataTypeUint return consts.DataTypeUint
case reflect.Bool: case reflect.Bool:
return DataTypeBool return consts.DataTypeBool
case reflect.Float32, reflect.Float64: case reflect.Float32, reflect.Float64:
return DataTypeFloat return consts.DataTypeFloat64
default: default:
return DataTypeUnknown return consts.DataTypeUnknown
} }
} }
@ -87,51 +99,28 @@ func (at *AnyType) Type() string {
// //
// Date : 18:32 2023/6/1 // Date : 18:32 2023/6/1
func (at *AnyType) ToString() String { func (at *AnyType) ToString() String {
switch at.dataType { dataType := at.Type()
case DataTypeNil: switch dataType {
case consts.DataTypeUnknown, consts.DataTypeNil:
return String("") return String("")
case DataTypeObject: case consts.DataTypeString:
fallthrough return String(fmt.Sprintf("%v", at.data))
case DataTypeSlice: case consts.DataTypeSliceAny:
fallthrough var val []any
case DataTypePtr: _ = serialize.JSON.Transition(at.data, &val)
return String(serialize.JSON.MarshalForString(at.data)) return String(ArrayType[any](val).ToString().Value)
} case consts.DataTypeMapAnyAny:
return String(fmt.Sprintf("%v", at.data)) easyMap := EasyMap(at.data)
} return String(easyMap.ToString())
case consts.DataTypeInt:
// ToObject 任意类型转为对象 return String(Int(at.data.(int64)).ToString().Value)
// case consts.DataTypeUint:
// Author : go_developer@163.com<白茶清欢> return String(Int(at.data.(uint)).ToString().Value)
// case consts.DataTypeFloat64:
// Date : 17:19 2023/10/11 return String(Float(at.data.(float64)).ToString().Value)
func (at *AnyType) ToObject() MapResult { case consts.DataTypeBool:
return MapResult{ return String(fmt.Sprintf("%v", at.data))
Value: EasyMapFromString(at.ToString().Value()), default:
Err: nil, return String(serialize.JSON.MarshalForStringIgnoreError(at.data))
} }
} }
func (at *AnyType) ToIntSlice() {
}
func (at *AnyType) ToUintSlice() {
}
func (at *AnyType) ToStringSlice() {
}
func (at *AnyType) ToFloatSlice() {
}
func (at *AnyType) ToBoolSlice() {
}
func (at *AnyType) ToAnySlice() {
}

View File

@ -10,6 +10,7 @@ package wrapper
import ( import (
"encoding/json" "encoding/json"
"git.zhangdeman.cn/zhangdeman/op_type" "git.zhangdeman.cn/zhangdeman/op_type"
"github.com/tidwall/gjson"
"reflect" "reflect"
"strings" "strings"
) )
@ -54,8 +55,8 @@ func (at *Array[Bt]) IsNil() bool {
func (at *Array[Bt]) ToStringSlice() []string { func (at *Array[Bt]) ToStringSlice() []string {
list := make([]string, 0) list := make([]string, 0)
for _, item := range at.value { for _, item := range at.value {
byteData, _ := json.Marshal(item) str := AnyDataType(item).ToString().Value()
list = append(list, strings.Trim(string(byteData), "\"")) list = append(list, str)
} }
return list return list
} }
@ -142,3 +143,24 @@ func (at *Array[Bt]) ToStringWithSplit(split string) StringResult {
Err: nil, Err: nil,
} }
} }
// ExtraField 提取[]map/[]struct 中的指定字段, 并以list形式返回
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 19:00 2024/10/13
func (at *Array[Bt]) ExtraField(fieldName string) String {
if at.IsNil() {
return String("[]")
}
byteData, _ := json.Marshal(at.value)
res := make([]any, 0)
list := gjson.ParseBytes(byteData).Array()
for _, item := range list {
itemValue := item.Get(fieldName)
if itemValue.Exists() {
res = append(res, itemValue.Value())
}
}
return String(ArrayType(res).ToString().Value)
}

118
bigint.go Normal file
View File

@ -0,0 +1,118 @@
// Package wrapper ...
//
// Description : wrapper ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-11-19 16:33
package wrapper
import (
"database/sql/driver"
"fmt"
"reflect"
"strconv"
)
// BigInt 是一个自定义类型用于在JSON编码时将int64转换为字符串。
// 建议只在Output中使用它Input时直接使用int64。
type BigInt string
var EmptyBigInt BigInt = "0"
func (f *BigInt) IsNil() bool {
if nil == f {
return true
}
return reflect.ValueOf(*f).IsNil()
}
// MarshalJSON 自定义的JSON编码逻辑。
// @implements json.Marshaler
func (f *BigInt) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf(`"%d"`, f.Int64())), nil
}
// ToString 返回BigId的字符串表示。
func (f *BigInt) String() string {
if f.IsNil() {
return string(EmptyBigInt)
}
return string(*f)
}
// Value 在orm写入数据库时会调用它进行格式转换.
// @implements database/sql/driver.Valuer
func (f *BigInt) Value() (driver.Value, error) {
if f.IsNil() {
return 0, nil
}
return f.Uint64(), nil
}
// Int64 返回BigId的int64表示。
// @implements github.com/gogf/gf/v2/util/gconv.iInt64
func (f *BigInt) Int64() int64 {
if f.IsNil() {
return 0
}
i, err := strconv.ParseInt(string(*f), 10, 64)
if err != nil || i <= 0 {
return 0
}
return i
}
// Uint64 返回BigId的uint64表示。
// @implements github.com/gogf/gf/v2/util/gconv.iUint64
func (f *BigInt) Uint64() uint64 {
if f.IsNil() {
return 0
}
return uint64(f.Int64())
}
// IsEmpty 判断BigId是否为空
func (f *BigInt) IsEmpty() bool {
if f.IsNil() {
return true
}
return *f == "" || *f == EmptyBigInt || f.Int64() == 0
}
// UnmarshalJSON converts a json byte array of a big ID into an BigInt type.
// @implements json.Unmarshaler
func (f *BigInt) UnmarshalJSON(b []byte) error {
var (
s = string(b)
)
// 如果是null设置为0
if s == "null" || s == "" || s == "0" {
*f = EmptyBigInt
return nil
}
// 如果是字符串,去掉引号
if len(b) >= 3 && b[0] == '"' && b[len(b)-1] == '"' {
s = string(b[1 : len(b)-1])
}
*f = StrToBigInt(s)
return nil
}
// ToBigInt 将int转换为BigInt
func ToBigInt(id int64) BigInt {
if id <= 0 {
return EmptyBigInt
}
return BigInt(fmt.Sprintf("%d", id))
}
// StrToBigInt 将str转换为BigInt类型
func StrToBigInt(id string) BigInt {
i, err := strconv.ParseInt(id, 10, 64)
if err != nil || i <= 0 {
return EmptyBigInt
}
return BigInt(id)
}

View File

@ -38,7 +38,7 @@ var errNilPtr = errors.New("destination pointer is nil") // embedded in descript
// convertAssign copies to dest the value in src, converting it if possible. // convertAssign copies to dest the value in src, converting it if possible.
// An error is returned if the copy would result in loss of information. // An error is returned if the copy would result in loss of information.
// dest should be a pointer type. // dest should be a pointer type.
func ConvertAssign(dest, src interface{}) error { func ConvertAssign(dest, src any) error {
// Common cases, without reflect. // Common cases, without reflect.
switch s := src.(type) { switch s := src.(type) {
case string: case string:
@ -70,7 +70,7 @@ func ConvertAssign(dest, src interface{}) error {
} }
*d = string(s) *d = string(s)
return nil return nil
case *interface{}: case *any:
if d == nil { if d == nil {
return errNilPtr return errNilPtr
} }
@ -112,7 +112,7 @@ func ConvertAssign(dest, src interface{}) error {
} }
case nil: case nil:
switch d := dest.(type) { switch d := dest.(type) {
case *interface{}: case *any:
if d == nil { if d == nil {
return errNilPtr return errNilPtr
} }
@ -164,7 +164,7 @@ func ConvertAssign(dest, src interface{}) error {
*d = bv.(bool) *d = bv.(bool)
} }
return err return err
case *interface{}: case *any:
*d = src *d = src
return nil return nil
} }
@ -271,11 +271,11 @@ func cloneBytes(b []byte) []byte {
return c return c
} }
func ToString(src interface{}) string { func ToString(src any) string {
return asString(src) return asString(src)
} }
func asString(src interface{}) string { func asString(src any) string {
switch v := src.(type) { switch v := src.(type) {
case string: case string:
return v return v
@ -327,14 +327,14 @@ func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool) {
// []byte // []byte
// string // string
// time.Time // time.Time
type Value interface{} type Value any
type boolType struct{} type boolType struct{}
var Bool boolType var Bool boolType
func (boolType) String() string { return "Bool" } func (boolType) String() string { return "Bool" }
func (boolType) ConvertValue(src interface{}) (Value, error) { func (boolType) ConvertValue(src any) (Value, error) {
switch s := src.(type) { switch s := src.(type) {
case bool: case bool:
return s, nil return s, nil
@ -390,5 +390,5 @@ type Scanner interface {
// Reference types such as []byte are only valid until the next call to Scan // Reference types such as []byte are only valid until the next call to Scan
// and should not be retained. Their underlying memory is owned by the driver. // and should not be retained. Their underlying memory is owned by the driver.
// If retention is necessary, copy their values before the next call to Scan. // If retention is necessary, copy their values before the next call to Scan.
Scan(src interface{}) error Scan(src any) error
} }

View File

@ -7,19 +7,8 @@
// Date : 2023-05-05 14:44 // Date : 2023-05-05 14:44
package wrapper package wrapper
import "time" import (
"time"
const (
DataTypeUnknown = "unknown"
DataTypeNil = "nil"
DataTypePtr = "ptr"
DataTypeString = "string"
DataTypeInt = "int"
DataTypeUint = "uint"
DataTypeBool = "bool"
DataTypeFloat = "float"
DataTypeSlice = "slice"
DataTypeObject = "object"
) )
// Int8Result ... // Int8Result ...
@ -268,7 +257,7 @@ type Float64PtrResult struct {
// //
// Date : 16:40 2023/5/8 // Date : 16:40 2023/5/8
type Any struct { type Any struct {
Value interface{} Value any
Err error Err error
} }
@ -298,7 +287,7 @@ type BoolPtrResult struct {
// //
// Date : 16:38 2023/5/8 // Date : 16:38 2023/5/8
type ObjectResult struct { type ObjectResult struct {
Value map[string]interface{} Value map[string]any
Err error Err error
} }
@ -488,6 +477,6 @@ type MapResult struct {
// //
// Date : 18:28 2023/5/8 // Date : 18:28 2023/5/8
type AnySliceResult struct { type AnySliceResult struct {
Value []interface{} Value []any
Err error Err error
} }

86
easymap.go Normal file
View File

@ -0,0 +1,86 @@
// Package wrapper ...
//
// Description : wrapper ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2023-08-10 15:01
package wrapper
import (
"encoding/json"
"errors"
"git.zhangdeman.cn/zhangdeman/serialize"
"github.com/tidwall/gjson"
"reflect"
)
// EasyMap ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:02 2023/8/10
func EasyMap(mapData any) Map {
m, _ := EasyMapWithError(mapData)
return m
}
// EasyMapWithError 转换map并带上转换的异常
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:06 2023/8/10
func EasyMapWithError(mapData any) (Map, error) {
if nil == mapData {
return map[string]any{}, nil
}
reflectType := reflect.TypeOf(mapData)
if reflectType.Kind() != reflect.Map {
mapFormatData := make(map[string]any)
if err := serialize.JSON.UnmarshalWithNumber(serialize.JSON.MarshalForByteIgnoreError(mapData), &mapFormatData); nil != err {
return mapFormatData, errors.New("input data type is " + reflectType.String() + ", can not convert to map")
}
return mapFormatData, nil
}
m := Map(map[string]any{})
reflectValue := reflect.ValueOf(mapData).MapRange()
for reflectValue.Next() {
// 循环提取相关值
_ = m.Set(reflectValue.Key().String(), reflectValue.Value().Interface())
}
return m, nil
}
// EasyMapFromStruct 从struct转map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:11 2023/8/10
func EasyMapFromStruct(data any) Map {
byteData, _ := json.Marshal(data)
return EasyMapFromByte(byteData)
}
// EasyMapFromString 从string转为Map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:12 2023/8/10
func EasyMapFromString(data string) Map {
return EasyMapFromByte([]byte(data))
}
// EasyMapFromByte 从字节数组转为Map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:12 2023/8/10
func EasyMapFromByte(data []byte) Map {
res := Map(map[string]any{})
jsonRes := gjson.Parse(string(data))
jsonRes.ForEach(func(key, value gjson.Result) bool {
_ = res.Set(key.String(), value.Value())
return true
})
return res
}

View File

@ -107,7 +107,7 @@ func (f Float) ToString() StringResult {
} }
} }
return StringResult{ return StringResult{
Value: fmt.Sprintf("%v", floatVal), Value: fmt.Sprintf("%v", floatVal.Value),
Err: nil, Err: nil,
} }
} }

19
go.mod
View File

@ -5,22 +5,25 @@ go 1.21
toolchain go1.21.4 toolchain go1.21.4
require ( require (
git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211 git.zhangdeman.cn/zhangdeman/consts v0.0.0-20250321102241-d6e86b64f7ca
git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20240325080031-1f58204e8687 git.zhangdeman.cn/zhangdeman/op_type v0.0.0-20240122104027-4928421213c0
git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20241223084948-de2e49144fcd
git.zhangdeman.cn/zhangdeman/util v0.0.0-20240618042405-6ee2c904644e
github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394 github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394
github.com/stretchr/testify v1.8.4 github.com/mitchellh/mapstructure v1.5.0
github.com/spaolacci/murmur3 v1.1.0
github.com/stretchr/testify v1.9.0
github.com/tidwall/gjson v1.18.0
) )
require ( require (
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240501142503-e31a270e50cc // indirect github.com/BurntSushi/toml v1.5.0 // indirect
git.zhangdeman.cn/zhangdeman/op_type v0.0.0-20240122104027-4928421213c0 // indirect
git.zhangdeman.cn/zhangdeman/util v0.0.0-20231227095334-7eb5cdbf9253 // indirect
github.com/BurntSushi/toml v1.3.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect github.com/davecgh/go-spew v1.1.1 // indirect
github.com/go-ini/ini v1.67.0 // indirect github.com/go-ini/ini v1.67.0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mozillazg/go-pinyin v0.20.0 // indirect github.com/mozillazg/go-pinyin v0.20.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spaolacci/murmur3 v1.1.0 // indirect github.com/tidwall/match v1.1.1 // indirect
github.com/tidwall/pretty v1.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

59
go.sum
View File

@ -1,23 +1,33 @@
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240104123641-b3f23974e5d6 h1:ytpXTP3oxp480BAZQoOzqlBP4XP73NcpMplZ1/fA1lQ= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20241104082108-0f97a870bbc3 h1:BiAlBJ+DuRs/xD7nDQD2JT8Oc+V+0Uwt36qZwdXGvzI=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240104123641-b3f23974e5d6/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20241104082108-0f97a870bbc3/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240419080457-9d9562469008 h1:6z99+X/B/G9sCZ+aTLYGWk3YLVVODzevA4wjWj9jvq0= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20241125061350-1f5050978fc3 h1:/40XIygeSxRhPQc3/7pKGpV5hg8jwrMwh1+YiyCHdNI=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240419080457-9d9562469008/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20241125061350-1f5050978fc3/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240501142503-e31a270e50cc h1:kPz9xiUVruM8kwbUUVpxyCTX8pGgyKt60K5zX77oyC4= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20241125065114-f919222003d9 h1:TP/M3WnGsxh0Vr6YuS1i28hw1oV//YbdCoI46PUBIA0=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20240501142503-e31a270e50cc/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20241125065114-f919222003d9/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k=
git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240130062251-a87a97b0e8d4 h1:93JYY8JLbFcrlq37q/uKyxs2r2e3modsjvfSbnZQ/UI= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20241125100843-b1b286c7a701 h1:G+lGQmjMOBWGspZfijZvenGUAKpjBBrkRXLg3+GZp0U=
git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240130062251-a87a97b0e8d4/go.mod h1:SrtvrQRdzt+8KfYzvosH++gWxo2ShPTzR1m3VQ6uX7U= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20241125100843-b1b286c7a701/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k=
git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211 h1:I/wOsRpCSRkU9vo1u703slQsmK0wnNeZzsWQOGtIAG0= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20250122075709-5ecf3edb4a00 h1:obyJF0CXVR93TOnOtzN5xXxxSLpw1UFMBc4niWiyoQI=
git.zhangdeman.cn/zhangdeman/easymap v0.0.0-20240311030808-e2a2e6a3c211/go.mod h1:SrtvrQRdzt+8KfYzvosH++gWxo2ShPTzR1m3VQ6uX7U= git.zhangdeman.cn/zhangdeman/consts v0.0.0-20250122075709-5ecf3edb4a00/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20250227040546-863c03f34bb8 h1:VEifPc+vkpEQoX9rj7zxmT1m+IA81XjOxe7+Z1aqWNM=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20250227040546-863c03f34bb8/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20250321102241-d6e86b64f7ca h1:uxjzbY5fDozjyK6jkoQtuQouVTcVfXjbe3chARYSjRM=
git.zhangdeman.cn/zhangdeman/consts v0.0.0-20250321102241-d6e86b64f7ca/go.mod h1:IXXaZkb7vGzGnGM5RRWrASAuwrVSNxuoe0DmeXx5g6k=
git.zhangdeman.cn/zhangdeman/op_type v0.0.0-20240122104027-4928421213c0 h1:gUDlQMuJ4xNfP2Abl1Msmpa3fASLWYkNlqDFF/6GN0Y= git.zhangdeman.cn/zhangdeman/op_type v0.0.0-20240122104027-4928421213c0 h1:gUDlQMuJ4xNfP2Abl1Msmpa3fASLWYkNlqDFF/6GN0Y=
git.zhangdeman.cn/zhangdeman/op_type v0.0.0-20240122104027-4928421213c0/go.mod h1:VHb9qmhaPDAQDcS6vUiDCamYjZ4R5lD1XtVsh55KsMI= git.zhangdeman.cn/zhangdeman/op_type v0.0.0-20240122104027-4928421213c0/go.mod h1:VHb9qmhaPDAQDcS6vUiDCamYjZ4R5lD1XtVsh55KsMI=
git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20240110090803-399e964daa0c h1:k7VCn9GfRGTilvdF/TcTFVMDBfKLe3VeGAtMTiDSnS0= git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20241104092308-ecb02113459e h1:A045F67AMSqFKGD9kk2uLa+6c/zpmW8vjjSRmSsdjPs=
git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20240110090803-399e964daa0c/go.mod h1:w7kG4zyTJ1uPFaTWhze+OQuaUBINT2XnDxpyiM6ctc0= git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20241104092308-ecb02113459e/go.mod h1:XqgER4jDYwskFgj2riJ9XptIjzgYWubY+Zq8iB2WkY0=
git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20240325080031-1f58204e8687 h1:uQcGqdzi4UdpZlp4f4FUPeBqoygP58pEKJkmN3ROsE0= git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20241108082010-42ae8fe5ebdc h1:jtdEMr/xNchJDEoCnvMr4JXT9+biYQu625Cj+dz025w=
git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20240325080031-1f58204e8687/go.mod h1:gf7SW2TXATgux8pfdFedMkXWv2515OtIIM/5c4atkFw= git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20241108082010-42ae8fe5ebdc/go.mod h1:XqgER4jDYwskFgj2riJ9XptIjzgYWubY+Zq8iB2WkY0=
git.zhangdeman.cn/zhangdeman/util v0.0.0-20231227095334-7eb5cdbf9253 h1:GO3oZa5a2sqwAzGcLDJtQzmshSWRmoP7IDS8bwFqvC4= git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20241125105403-cb92be844edc h1:rYjlMH5Yy0G8OQgXA8qrV+fqObnB99v+6s8nbiLhzQs=
git.zhangdeman.cn/zhangdeman/util v0.0.0-20231227095334-7eb5cdbf9253/go.mod h1:VpPjBlwz8U+OxZuxzHQBv1aEEZ3pStH6bZvT21ADEbI= git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20241125105403-cb92be844edc/go.mod h1:+D6uPSljwHywjVY5WSBY4TRVMj26TN5f5cFGEYMldjs=
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8= git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20241223084948-de2e49144fcd h1:q7GG14qgXKB4MEXQFOe7/UYebsqMfPaSX80TcPdOosI=
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= git.zhangdeman.cn/zhangdeman/serialize v0.0.0-20241223084948-de2e49144fcd/go.mod h1:+D6uPSljwHywjVY5WSBY4TRVMj26TN5f5cFGEYMldjs=
git.zhangdeman.cn/zhangdeman/util v0.0.0-20240618042405-6ee2c904644e h1:Q973S6CcWr1ICZhFI1STFOJ+KUImCl2BaIXm6YppBqI=
git.zhangdeman.cn/zhangdeman/util v0.0.0-20240618042405-6ee2c904644e/go.mod h1:VpPjBlwz8U+OxZuxzHQBv1aEEZ3pStH6bZvT21ADEbI=
github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394 h1:OYA+5W64v3OgClL+IrOD63t4i/RW7RqrAVl9LTZ9UqQ= github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394 h1:OYA+5W64v3OgClL+IrOD63t4i/RW7RqrAVl9LTZ9UqQ=
github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394/go.mod h1:Q8n74mJTIgjX4RBBcHnJ05h//6/k6foqmgE45jTQtxg= github.com/axgle/mahonia v0.0.0-20180208002826-3358181d7394/go.mod h1:Q8n74mJTIgjX4RBBcHnJ05h//6/k6foqmgE45jTQtxg=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@ -26,14 +36,23 @@ github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/mozillazg/go-pinyin v0.20.0 h1:BtR3DsxpApHfKReaPO1fCqF4pThRwH9uwvXzm+GnMFQ= github.com/mozillazg/go-pinyin v0.20.0 h1:BtR3DsxpApHfKReaPO1fCqF4pThRwH9uwvXzm+GnMFQ=
github.com/mozillazg/go-pinyin v0.20.0/go.mod h1:iR4EnMMRXkfpFVV5FMi4FNB6wGq9NV6uDWbUuPhP4Yc= github.com/mozillazg/go-pinyin v0.20.0/go.mod h1:iR4EnMMRXkfpFVV5FMi4FNB6wGq9NV6uDWbUuPhP4Yc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI= github.com/spaolacci/murmur3 v1.1.0 h1:7c1g84S4BPRrfL5Xrdp6fOJ206sU9y293DDHaoy0bLI=
github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk=
github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA=
github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM=
github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4=
github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=

313
map.go
View File

@ -4,92 +4,283 @@
// //
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 2023-08-10 15:01 // Date : 2024-11-06 18:27
package wrapper package wrapper
import ( import (
"encoding/json"
"errors" "errors"
"git.zhangdeman.cn/zhangdeman/easymap"
"git.zhangdeman.cn/zhangdeman/serialize" "git.zhangdeman.cn/zhangdeman/serialize"
"github.com/tidwall/gjson"
"reflect" "reflect"
"sync"
) )
// EasyMap ... var mapLock = &sync.RWMutex{}
type Map map[string]any
func (m Map) lock() {
mapLock.Lock()
}
func (m Map) unlock() {
mapLock.Unlock()
}
func (m Map) rLock() {
mapLock.RLock()
}
func (m Map) rUnlock() {
mapLock.RUnlock()
}
// Exist key是否存在
// //
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 15:02 2023/8/10 // Date : 18:34 2024/11/6
func EasyMap(mapData interface{}) Map { func (m Map) Exist(key string) bool {
m, _ := EasyMapWithError(mapData) if m.IsNil() {
return false
}
m.rLock()
defer m.rUnlock()
_, exist := m[key]
return exist
}
// Set 设置map的值, 字段如果已存在, 会覆盖
//
// 参数说明:
// - field : 摇摆存的字段
// - value : 字段对应的值
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:16 2024/11/19
func (m Map) Set(field string, value any) error {
if m.IsNil() {
return errors.New("Map is nil")
}
m.lock()
defer m.unlock()
m[field] = value
return nil
}
// Del 删除指定的字段
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:21 2024/11/19
func (m Map) Del(field string) {
if m.IsNil() {
return
}
m.lock()
defer m.unlock()
delete(m, field)
}
// IsNil 判断map是否为nil
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:22 2024/11/19
func (m Map) IsNil() bool {
if nil == m {
return true
}
return reflect.ValueOf(m).IsNil()
}
// Get ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:41 2024/11/19
func (m Map) Get(field string) (any, error) {
if m.IsNil() {
return nil, errors.New("map is nil")
}
m.rLock()
defer m.rUnlock()
val, exist := m[field]
if !exist {
return nil, errors.New(field + " : field not found")
}
return val, nil
}
// GetDefault 获取指定字段, 不存在则设置默认值
//
// 参数说明:
// - field : 要读取的字段
// - defaultValue : 字段不存在返回的默认值
// - allowNil : 字段存在, 但是值为Nil, 是否是一个合法值
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:59 2024/11/19
func (m Map) GetDefault(field string, defaultValue any, allowNil bool) any {
if m.IsNil() {
return defaultValue
}
m.rLock()
defer m.rUnlock()
val, exist := m[field]
if !exist {
return defaultValue
}
if nil == val {
if allowNil {
return val
}
return defaultValue
}
return val
}
// Value 获取数据值
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 19:39 2024/11/6
func (m Map) Value() map[string]any {
if m.IsNil() {
return nil
}
return m return m
} }
// EasyMapWithError 转换map并带上转换的异常 // Clone 克隆数据
// //
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 15:06 2023/8/10 // Date : 19:40 2024/11/6
func EasyMapWithError(mapData interface{}) (Map, error) { func (m Map) Clone() Map {
if nil == mapData { newData := map[string]any{}
return easymap.NewNormal(), nil if m.IsNil() {
return newData
} }
m := easymap.NewNormal() m.rLock()
reflectType := reflect.TypeOf(mapData) defer m.rUnlock()
if reflectType.Kind() != reflect.Map { mapValue := m.Value()
mapFormatData := make(map[string]interface{}) for k, v := range mapValue {
if err := serialize.JSON.UnmarshalWithNumber(serialize.JSON.MarshalForByte(mapData), &mapFormatData); nil != err { newData[k] = v
return m, errors.New("input data type is " + reflectType.String() + ", can not convert to map") }
return newData
}
// Filter 过滤指定字段
//
// 参数说明:
// - fieldList : 要保留的字段列表
// - ignoreNotFound : 指定字段不存在是否忽略,如不忽略, 字段不存在, 将会报错
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:40 2024/11/19
func (m Map) Filter(fieldList []string, ignoreNotFound bool) (map[string]any, error) {
res := make(map[string]any)
for _, itemField := range fieldList {
if val, err := m.Get(itemField); err == nil {
res[itemField] = val
} else {
if !ignoreNotFound {
return nil, err
}
} }
mapData = mapFormatData
} }
return res, nil
}
reflectValue := reflect.ValueOf(mapData).MapRange() // FilterDefault 过滤指定字段, 字段不存储在则用默认值填充
for reflectValue.Next() { //
// 循环提取相关值 // 参数说明:
m.Set(reflectValue.Key().Interface(), reflectValue.Value().Interface()) // - fieldMap : 查询字段表, key为要查询的字段, value为 字段不存在时返回的默认值
// - allowNil : 字段存在, 三只值为你来是否是一个合法值
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:07 2024/11/19
func (m Map) FilterDefault(fieldMap map[string]any, allowNil bool) map[string]any {
res := make(map[string]any)
for itemField, fieldDefaultValue := range fieldMap {
res[itemField] = m.GetDefault(itemField, fieldDefaultValue, allowNil)
} }
return m, nil
}
// EasyMapFromStruct 从struct转map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:11 2023/8/10
func EasyMapFromStruct(data interface{}) Map {
byteData, _ := json.Marshal(data)
return EasyMapFromByte(byteData)
}
// EasyMapFromString 从string转为Map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:12 2023/8/10
func EasyMapFromString(data string) Map {
return EasyMapFromByte([]byte(data))
}
// EasyMapFromByte 从字节数组转为Map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:12 2023/8/10
func EasyMapFromByte(data []byte) Map {
res := easymap.NewNormal()
jsonRes := gjson.Parse(string(data))
jsonRes.ForEach(func(key, value gjson.Result) bool {
res.Set(key.Value(), value.Value())
return true
})
return res return res
} }
// Map ... // MarshalJSON Map序列化
// //
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 15:14 2023/8/10 // Date : 15:35 2024/11/19
type Map easymap.EasyMap func (m Map) MarshalJSON() ([]byte, error) {
mapData := m.Value()
if nil == mapData {
return nil, nil
}
return serialize.JSON.MarshalForByte(mapData)
}
// ToString 序列化成字符串
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 14:24 2024/11/21
func (m Map) ToString() string {
byteData, _ := m.MarshalJSON()
return string(byteData)
}
// GetString 获取字符串结果
//
// 参数说明:
// - field : 要查找的字段
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:15 2024/11/21
func (m Map) GetString(field string) (string, error) {
val, err := m.Get(field)
if nil != err {
return "", err
}
return AnyDataType(val).ToString().Value(), nil
}
// GetInt64 获取Int64值
//
// 参数说明:
// - field : 要查找的字段
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:18 2024/11/21
func (m Map) GetInt64(field string) (int64, error) {
val, err := m.Get(field)
if nil != err {
return 0, err
}
int64Res := AnyDataType(val).ToString().ToInt64()
return int64Res.Value, int64Res.Err
}
// GetFloat64 获取float64值
//
// 参数说明:
// - field : 要查找的字段
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:18 2024/11/21
func (m Map) GetFloat64(field string) (float64, error) {
val, err := m.Get(field)
if nil != err {
return 0, err
}
float64Res := AnyDataType(val).ToString().ToFloat64()
return float64Res.Value, float64Res.Err
}

47
map_test.go Normal file
View File

@ -0,0 +1,47 @@
// Package wrapper ...
//
// Description : wrapper ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-11-06 18:37
package wrapper
import (
"fmt"
"testing"
)
func TestMap_Exist(t *testing.T) {
testData := Map(map[string]any{
"name": "zhang",
})
fmt.Println(testData.Exist("name"))
fmt.Println(testData.Exist("age"))
}
func TestMap_IsNil(t *testing.T) {
var (
m Map
m1 *Map
)
fmt.Println(m.Set("a", 1))
fmt.Println(m.IsNil(), m1.IsNil())
}
func TestMap_IsMasher(t *testing.T) {
var (
m Map
m1 = Map(map[string]any{
"a": 1,
"b": m,
"c": Map(map[string]any{
"name": "de",
}),
})
)
d, err := m.MarshalJSON()
fmt.Println(string(d), err)
d, err = m1.MarshalJSON()
fmt.Println(string(d), err)
}

View File

@ -19,10 +19,10 @@ import (
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 18:36 2023/6/1 // Date : 18:36 2023/6/1
func ObjectData(data interface{}) *ObjectType { func ObjectData(data any) *ObjectType {
ot := &ObjectType{ ot := &ObjectType{
source: data, source: data,
data: map[interface{}]interface{}{}, data: map[any]any{},
byteData: []byte{}, byteData: []byte{},
isValid: true, isValid: true,
invalidErr: errors.New("data is invalid"), invalidErr: errors.New("data is invalid"),
@ -49,8 +49,8 @@ func ObjectData(data interface{}) *ObjectType {
// //
// Date : 18:38 2023/6/1 // Date : 18:38 2023/6/1
type ObjectType struct { type ObjectType struct {
source interface{} source any
data map[interface{}]interface{} data map[any]any
byteData []byte byteData []byte
isValid bool isValid bool
invalidErr error invalidErr error
@ -71,7 +71,10 @@ func (ot *ObjectType) IsValid() bool {
// //
// Date : 18:50 2023/6/1 // Date : 18:50 2023/6/1
func (ot *ObjectType) IsNil() bool { func (ot *ObjectType) IsNil() bool {
return ot.source == nil if ot.source == nil {
return true
}
return reflect.ValueOf(ot.source).IsNil()
} }
// ToString 转字符串 // ToString 转字符串
@ -106,7 +109,7 @@ func (ot *ObjectType) ToString() StringResult {
// Date : 16:17 2023/6/2 // Date : 16:17 2023/6/2
func (ot *ObjectType) ToMapStringAny() ObjectResult { func (ot *ObjectType) ToMapStringAny() ObjectResult {
res := ObjectResult{ res := ObjectResult{
Value: map[string]interface{}{}, Value: map[string]any{},
Err: nil, Err: nil,
} }
if ot.IsNil() { if ot.IsNil() {
@ -121,7 +124,7 @@ func (ot *ObjectType) ToMapStringAny() ObjectResult {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 16:41 2023/6/2 // Date : 16:41 2023/6/2
func (ot *ObjectType) ToStruct(receiver interface{}) error { func (ot *ObjectType) ToStruct(receiver any) error {
if nil == receiver { if nil == receiver {
return errors.New("receiver is nil") return errors.New("receiver is nil")
} }
@ -136,7 +139,7 @@ func (ot *ObjectType) ToStruct(receiver interface{}) error {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 16:42 2023/6/2 // Date : 16:42 2023/6/2
func (ot *ObjectType) ToStructIgnoreErr(receiver interface{}) { func (ot *ObjectType) ToStructIgnoreErr(receiver any) {
if nil == receiver { if nil == receiver {
return return
} }

View File

@ -13,6 +13,7 @@ import (
"errors" "errors"
"git.zhangdeman.cn/zhangdeman/serialize" "git.zhangdeman.cn/zhangdeman/serialize"
"github.com/axgle/mahonia" "github.com/axgle/mahonia"
"github.com/spaolacci/murmur3"
"io" "io"
"math/rand" "math/rand"
"strings" "strings"
@ -521,7 +522,7 @@ func (str String) ToStringPtr() StringPtrResult {
func (str String) ToObject() ObjectResult { func (str String) ToObject() ObjectResult {
var ( var (
res = ObjectResult{ res = ObjectResult{
Value: map[string]interface{}{}, Value: map[string]any{},
Err: nil, Err: nil,
} }
) )
@ -534,7 +535,7 @@ func (str String) ToObject() ObjectResult {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 18:38 2023/5/4 // Date : 18:38 2023/5/4
func (str String) ToStruct(receiver interface{}) error { func (str String) ToStruct(receiver any) error {
if nil == receiver { if nil == receiver {
return errors.New("receiver is nil") return errors.New("receiver is nil")
} }
@ -992,7 +993,7 @@ func (str String) ToStringSlice(splitChar ...string) StringSliceResult {
// Date : 15:01 2023/5/5 // Date : 15:01 2023/5/5
func (str String) ToAnySlice(splitCharList ...string) AnySliceResult { func (str String) ToAnySlice(splitCharList ...string) AnySliceResult {
result := AnySliceResult{ result := AnySliceResult{
Value: []interface{}{}, Value: []any{},
Err: nil, Err: nil,
} }
@ -1002,7 +1003,7 @@ func (str String) ToAnySlice(splitCharList ...string) AnySliceResult {
} }
valArr := strings.Split(str.Value(), splitCharList[0]) valArr := strings.Split(str.Value(), splitCharList[0])
valList := make([]interface{}, 0) valList := make([]any, 0)
for _, item := range valArr { for _, item := range valArr {
v := String(item) v := String(item)
if res := v.ToInt64(); nil == res.Err { if res := v.ToInt64(); nil == res.Err {
@ -1175,3 +1176,15 @@ func (str String) HasSubStr(subStrList []string) bool {
} }
return false return false
} }
// HashNumber ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 11:05 2024/6/27
func (str String) HashNumber() Uint64Result {
return Uint64Result{
Value: murmur3.Sum64([]byte(str.Value())),
Err: nil,
}
}

View File

@ -17,7 +17,7 @@ import (
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 16:07 2023/8/10 // Date : 16:07 2023/8/10
func NewStruct(data interface{}) *Struct { func NewStruct(data any) *Struct {
s, _ := NewStructWithError(data) s, _ := NewStructWithError(data)
return s return s
} }
@ -27,7 +27,7 @@ func NewStruct(data interface{}) *Struct {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 16:17 2023/8/10 // Date : 16:17 2023/8/10
func NewStructWithError(data interface{}) (*Struct, error) { func NewStructWithError(data any) (*Struct, error) {
if data == nil { if data == nil {
return nil, errors.New("input data is nil") return nil, errors.New("input data is nil")
} }
@ -47,7 +47,7 @@ func NewStructWithError(data interface{}) (*Struct, error) {
// //
// Date : 16:05 2023/8/10 // Date : 16:05 2023/8/10
type Struct struct { type Struct struct {
data interface{} data any
} }
// ToMap 转为Map // ToMap 转为Map
@ -58,7 +58,7 @@ type Struct struct {
func (s *Struct) ToMap() MapResult { func (s *Struct) ToMap() MapResult {
if nil == s.data { if nil == s.data {
return MapResult{ return MapResult{
Value: EasyMap(map[interface{}]interface{}{}), Value: EasyMap(map[any]any{}),
Err: nil, Err: nil,
} }
} }

View File

@ -69,12 +69,12 @@ type CustomDiffFunc func(field string, inputVal wrapper.Map, storageVal wrapper.
// //
// Date : 11:10 2024/3/8 // Date : 11:10 2024/3/8
type DiffResult struct { type DiffResult struct {
Field string `json:"field"` // 字段名 Field string `json:"field"` // 字段名
OldVal interface{} `json:"old_val"` // 当前field在storageVal中的值 OldVal any `json:"old_val"` // 当前field在storageVal中的值
NewVal interface{} `json:"new_val"` // 当前field在inputVal中的值 NewVal any `json:"new_val"` // 当前field在inputVal中的值
IsSame bool `json:"is_same"` // 两个值是否相同 IsSame bool `json:"is_same"` // 两个值是否相同
DiffReason string `json:"diff_reason"` // 两个值不同的原因 DiffReason string `json:"diff_reason"` // 两个值不同的原因
Err error `json:"err"` // 对比过程中是否出现异常 Err error `json:"err"` // 对比过程中是否出现异常
} }
const ( const (
@ -86,7 +86,7 @@ const (
var ( var (
// 当前仅支持基础类型的比较不支持slice/map/struct等复杂类型的比较 // 当前仅支持基础类型的比较不支持slice/map/struct等复杂类型的比较
supportValueTypeTable = map[reflect.Kind]interface{}{ supportValueTypeTable = map[reflect.Kind]any{
reflect.Bool: true, reflect.Bool: true,
reflect.Int: true, reflect.Int: true,
reflect.Int8: true, reflect.Int8: true,
@ -135,22 +135,22 @@ func DefaultDiffFunc(field string, inputVal wrapper.Map, storageVal wrapper.Map,
Err: nil, Err: nil,
} }
var ( var (
inputFieldVal interface{} inputFieldVal any
inputFieldValExist bool inputFieldValExist error
storageFieldVal interface{} storageFieldVal any
storageFieldValExist bool storageFieldValExist error
) )
inputFieldVal, inputFieldValExist = inputVal.Get(field) inputFieldVal, inputFieldValExist = inputVal.Get(field)
storageFieldVal, storageFieldValExist = storageVal.Get(field) storageFieldVal, storageFieldValExist = storageVal.Get(field)
// 字段在输入数据和存储数据中均不存在 // 字段在输入数据和存储数据中均不存在
if !inputFieldValExist && !storageFieldValExist { if nil != inputFieldValExist && nil != storageFieldValExist {
// 输入和存储都没这个字段 // 输入和存储都没这个字段
return result return result
} }
// 判断输入字段是否存在 // 判断输入字段是否存在
if !inputFieldValExist { if nil != inputFieldValExist {
if option.IgnoreNotFoundField { if option.IgnoreNotFoundField {
// 忽略不存在的字段 // 忽略不存在的字段
return result return result
@ -162,7 +162,7 @@ func DefaultDiffFunc(field string, inputVal wrapper.Map, storageVal wrapper.Map,
return result return result
} }
// 判断存储字段是否存在 // 判断存储字段是否存在
if !storageFieldValExist { if nil != storageFieldValExist {
result.IsSame = false result.IsSame = false
result.DiffReason = DiffReasonStorageFieldNotFound result.DiffReason = DiffReasonStorageFieldNotFound
result.NewVal = inputFieldVal result.NewVal = inputFieldVal

View File

@ -20,13 +20,13 @@ func TestDefaultDiffFunc(t *testing.T) {
num3 string = "1" num3 string = "1"
num4 string = "1.00" num4 string = "1.00"
) )
input := wrapper.EasyMap(map[string]interface{}{ input := wrapper.EasyMap(map[string]any{
"num": num1, "num": num1,
"num3": num3, "num3": num3,
"num4": num4, "num4": num4,
"num5": num1, "num5": num1,
}) })
storage := wrapper.EasyMap(map[string]interface{}{ storage := wrapper.EasyMap(map[string]any{
"num": num2, "num": num2,
"num3": num2, "num3": num2,
"num4": num2, "num4": num2,

View File

@ -13,8 +13,8 @@ package try
// //
// Date : 11:26 2023/7/20 // Date : 11:26 2023/7/20
type ICatchHandler interface { type ICatchHandler interface {
Catch(errCode string, handler func(errCode string, data map[string]interface{})) ICatchHandler Catch(errCode string, handler func(errCode string, data map[string]any)) ICatchHandler
CatchAll(handler func(errCode string, data map[string]interface{})) IFinalHandler CatchAll(handler func(errCode string, data map[string]any)) IFinalHandler
IFinalHandler IFinalHandler
} }
@ -24,7 +24,7 @@ type ICatchHandler interface {
// //
// Date : 11:27 2023/7/20 // Date : 11:27 2023/7/20
type IFinalHandler interface { type IFinalHandler interface {
Finally(data map[string]interface{}, handlers ...func(data map[string]interface{})) Finally(data map[string]any, handlers ...func(data map[string]any))
} }
// ILogicFunction 逻辑函数约束 // ILogicFunction 逻辑函数约束

View File

@ -15,7 +15,7 @@ package try
type DefaultCatchHandler struct { type DefaultCatchHandler struct {
hasDeal bool // 异常是否已被处理 hasDeal bool // 异常是否已被处理
errCode string errCode string
data map[string]interface{} data map[string]any
} }
// hasDealError 判断异常是否已经被处理 // hasDealError 判断异常是否已经被处理
@ -38,7 +38,7 @@ func (d *DefaultCatchHandler) hasDealError() bool {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 17:19 2023/7/20 // Date : 17:19 2023/7/20
func (d *DefaultCatchHandler) Catch(errCode string, handler func(errCode string, data map[string]interface{})) ICatchHandler { func (d *DefaultCatchHandler) Catch(errCode string, handler func(errCode string, data map[string]any)) ICatchHandler {
if d.hasDealError() { if d.hasDealError() {
return d return d
} }
@ -61,7 +61,7 @@ func (d *DefaultCatchHandler) Catch(errCode string, handler func(errCode string,
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 17:47 2023/7/20 // Date : 17:47 2023/7/20
func (d *DefaultCatchHandler) CatchAll(handler func(errCode string, data map[string]interface{})) IFinalHandler { func (d *DefaultCatchHandler) CatchAll(handler func(errCode string, data map[string]any)) IFinalHandler {
if d.hasDealError() { if d.hasDealError() {
return d return d
} }
@ -80,9 +80,9 @@ func (d *DefaultCatchHandler) CatchAll(handler func(errCode string, data map[str
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 17:48 2023/7/20 // Date : 17:48 2023/7/20
func (d *DefaultCatchHandler) Finally(data map[string]interface{}, handlers ...func(data map[string]interface{})) { func (d *DefaultCatchHandler) Finally(data map[string]any, handlers ...func(data map[string]any)) {
if data == nil { if data == nil {
data = map[string]interface{}{} data = map[string]any{}
} }
defer func() { defer func() {
if r := recover(); nil != r { if r := recover(); nil != r {

View File

@ -13,7 +13,7 @@ package try
// //
// Date : 11:30 2023/7/20 // Date : 11:30 2023/7/20
type LogicFuncInput struct { type LogicFuncInput struct {
Parameter map[string]interface{} Parameter map[string]any
} }
// LogicFuncOutput ... // LogicFuncOutput ...
@ -22,8 +22,8 @@ type LogicFuncInput struct {
// //
// Date : 11:30 2023/7/20 // Date : 11:30 2023/7/20
type LogicFuncOutput struct { type LogicFuncOutput struct {
ErrCode string // 错误标识码 ErrCode string // 错误标识码
Data map[string]interface{} // 错误时返回的数据 Data map[string]any // 错误时返回的数据
} }
// NewLogicFuncOutput 获取逻辑函数输出数据 // NewLogicFuncOutput 获取逻辑函数输出数据
@ -31,9 +31,9 @@ type LogicFuncOutput struct {
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 11:33 2023/7/20 // Date : 11:33 2023/7/20
func NewLogicFuncOutput(code string, data map[string]interface{}) LogicFuncOutput { func NewLogicFuncOutput(code string, data map[string]any) LogicFuncOutput {
if data == nil { if data == nil {
data = map[string]interface{}{} data = map[string]any{}
} }
r := LogicFuncOutput{ r := LogicFuncOutput{
ErrCode: code, ErrCode: code,

View File

@ -22,14 +22,14 @@ func Try(fn ILogicFunction, input *LogicFuncInput) ICatchHandler {
defer func() { defer func() {
if r := recover(); r != nil { if r := recover(); r != nil {
catchHandler.errCode = LogicFuncPanic catchHandler.errCode = LogicFuncPanic
catchHandler.data = map[string]interface{}{ catchHandler.data = map[string]any{
"message": r.(error).Error(), "message": r.(error).Error(),
} }
} }
}() }()
if nil == input { if nil == input {
input = &LogicFuncInput{ input = &LogicFuncInput{
Parameter: map[string]interface{}{}, Parameter: map[string]any{},
} }
} }