tianyuan-api-server/apps/api/internal/common/logic.go
2025-06-14 15:20:36 +08:00

63 lines
1.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)
// 获取字段名(优先使用 json tag
key := field.Name
if jsonTag := field.Tag.Get("json"); jsonTag != "" && jsonTag != "-" {
key = jsonTag
}
// 处理字段值
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
}