60 lines
1.3 KiB
Go
60 lines
1.3 KiB
Go
package common
|
|
|
|
import (
|
|
"reflect"
|
|
)
|
|
|
|
// StructToMap 将结构体转换为 map[string]interface{}
|
|
func StructToMap(data interface{}) (map[string]interface{}, error) {
|
|
result := make(map[string]interface{})
|
|
|
|
// 使用反射获取结构体的值
|
|
v := reflect.ValueOf(data)
|
|
if v.Kind() == reflect.Ptr {
|
|
v = v.Elem()
|
|
}
|
|
if v.Kind() != reflect.Struct {
|
|
return nil, nil
|
|
}
|
|
|
|
// 遍历结构体字段
|
|
t := v.Type()
|
|
for i := 0; i < v.NumField(); i++ {
|
|
field := t.Field(i)
|
|
value := v.Field(i)
|
|
|
|
// 使用结构体字段名作为 key
|
|
key := field.Name
|
|
|
|
// 处理字段值
|
|
if value.IsValid() && !value.IsZero() {
|
|
if value.Kind() == reflect.Ptr {
|
|
value = value.Elem()
|
|
}
|
|
result[key] = value.Interface()
|
|
}
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
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
|
|
}
|