87 lines
2.1 KiB
Go
87 lines
2.1 KiB
Go
// 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
|
||
}
|