2024-10-12 20:41:55 +08:00
|
|
|
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)
|
|
|
|
|
2024-10-15 17:19:23 +08:00
|
|
|
// 检查字段的 encrypt 标签是否为 "false"
|
|
|
|
encryptTag := field.Tag.Get("encrypt")
|
|
|
|
if encryptTag == "false" {
|
2024-10-15 20:52:51 +08:00
|
|
|
encryptedFields[field.Name] = fieldValue.Interface()
|
2024-10-15 17:19:23 +08:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-10-12 20:41:55 +08:00
|
|
|
// 如果字段为空值,跳过
|
|
|
|
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
|
|
|
|
}
|