Files
jx-callback/globals/refutil/refutil.go

86 lines
2.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package refutil
import (
"bytes"
"encoding/base64"
"encoding/gob"
"fmt"
"reflect"
"git.rosy.net.cn/baseapi/utils"
)
func CheckAndGetStructValue(item interface{}) *reflect.Value {
value := reflect.ValueOf(item)
if value.Kind() == reflect.Ptr {
value = value.Elem()
} else {
panic("item ust be ptr type")
}
return &value
}
func GetObjFieldByName(obj interface{}, fieldName string) interface{} {
return reflect.Indirect(reflect.ValueOf(obj)).FieldByName(fieldName).Interface()
}
func SetObjFieldByName(obj interface{}, fieldName string, value interface{}) {
refValue := CheckAndGetStructValue(obj)
refValue.FieldByName(fieldName).Set(reflect.ValueOf(value))
}
func SerializeData(data interface{}) (strValue string, err error) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
if err = enc.Encode(data); err == nil {
strValue = base64.StdEncoding.EncodeToString(buf.Bytes())
return strValue, nil
}
return "", err
}
func DeSerializeData(strValue string, dataPtr interface{}) (err error) {
byteData, err := base64.StdEncoding.DecodeString(strValue)
if err == nil {
dec := gob.NewDecoder(bytes.NewReader(byteData))
return dec.Decode(dataPtr)
}
return err
}
// todo 这里看是否需要将key值转换成标准格式即字母大写因为beego orm不区分不转换也可以
func FilterMapByStructObject(mapData map[string]interface{}, obj interface{}, excludedFields []string, isCheckValue bool) (valid map[string]interface{}, invalid map[string]interface{}) {
excludedMap := make(map[string]int)
for _, v := range excludedFields {
excludedMap[v] = 1
}
m := utils.Struct2FlatMap(obj)
valid = make(map[string]interface{})
invalid = make(map[string]interface{})
for k, v := range mapData {
if m[k] != nil && excludedMap[k] == 0 && v != nil && (!isCheckValue || !IsValueEqual(m[k], v)) {
valid[k] = v
} else {
invalid[k] = v
}
}
return valid, invalid
}
func FilterMapByFieldList(mapData map[string]interface{}, fields []string) (valid map[string]interface{}, invalid map[string]interface{}) {
valid = make(map[string]interface{})
invalid = make(map[string]interface{})
for _, field := range fields {
if mapData[field] != nil {
valid[field] = mapData[field]
} else {
invalid[field] = mapData[field]
}
}
return valid, invalid
}
func IsValueEqual(value1, value2 interface{}) bool {
return fmt.Sprint(value1) == fmt.Sprint(value2)
}