92 lines
2.5 KiB
Go
92 lines
2.5 KiB
Go
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 IsFieldExist(obj interface{}, fieldName string) bool {
|
||
return reflect.Indirect(reflect.ValueOf(obj)).FieldByName(fieldName).IsValid()
|
||
}
|
||
|
||
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
|
||
m[k] = v
|
||
} else {
|
||
invalid[k] = v
|
||
}
|
||
}
|
||
utils.Map2Struct(m, obj, true, "")
|
||
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)
|
||
}
|