temp
This commit is contained in:
44
apps/api/internal/common/crypt.go
Normal file
44
apps/api/internal/common/crypt.go
Normal file
@@ -0,0 +1,44 @@
|
||||
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
|
||||
}
|
||||
21
apps/api/internal/common/logic.go
Normal file
21
apps/api/internal/common/logic.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package common
|
||||
|
||||
func MapStructToAPIRequest(encryptedFields map[string]interface{}, fieldMapping map[string]string, wrapField string) map[string]interface{} {
|
||||
apiRequest := make(map[string]interface{})
|
||||
|
||||
// 遍历字段映射表
|
||||
for structField, apiField := range fieldMapping {
|
||||
// 如果加密后的字段存在,才添加到请求
|
||||
if value, exists := encryptedFields[structField]; exists {
|
||||
apiRequest[apiField] = value
|
||||
}
|
||||
}
|
||||
|
||||
// 如果 wrapField 不为空,将 apiRequest 包裹到该字段下
|
||||
if wrapField != "" {
|
||||
return map[string]interface{}{
|
||||
wrapField: apiRequest,
|
||||
}
|
||||
}
|
||||
return apiRequest
|
||||
}
|
||||
Reference in New Issue
Block a user