45 lines
1.0 KiB
Go
45 lines
1.0 KiB
Go
|
package common
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"reflect"
|
||
|
"tianyuan-api/pkg/crypto"
|
||
|
)
|
||
|
|
||
|
// EncryptFields 加密字段的函数,处理不同类型,并跳过空值字段
|
||
|
func EncryptStructFields(inputStruct interface{}, key string) (map[string]interface{}, error) {
|
||
|
encryptedFields := make(map[string]interface{})
|
||
|
|
||
|
// 使用反射获取结构体的类型和值
|
||
|
v := reflect.ValueOf(inputStruct)
|
||
|
if v.Kind() != reflect.Struct {
|
||
|
return nil, errors.New("input is not a struct")
|
||
|
}
|
||
|
|
||
|
// 遍历结构体字段
|
||
|
for i := 0; i < v.NumField(); i++ {
|
||
|
field := v.Type().Field(i)
|
||
|
fieldValue := v.Field(i)
|
||
|
|
||
|
// 如果字段为空值,跳过
|
||
|
if fieldValue.IsZero() {
|
||
|
continue
|
||
|
}
|
||
|
|
||
|
// 将字段的值转换为字符串进行加密
|
||
|
strValue := fmt.Sprintf("%v", fieldValue.Interface())
|
||
|
|
||
|
// 执行加密操作
|
||
|
encryptedValue, err := crypto.WestDexEncrypt(strValue, key)
|
||
|
if err != nil {
|
||
|
return nil, err
|
||
|
}
|
||
|
|
||
|
// 将加密后的值存入结果映射
|
||
|
encryptedFields[field.Name] = encryptedValue
|
||
|
}
|
||
|
|
||
|
return encryptedFields, nil
|
||
|
}
|