-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathmapper_func.go
More file actions
245 lines (202 loc) · 5.58 KB
/
mapper_func.go
File metadata and controls
245 lines (202 loc) · 5.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package mapper
import (
"errors"
"reflect"
"sync"
)
// ============ 字段映射缓存 ============
// fieldMappingCache 字段映射缓存
// key: fromType -> toType, value: field mappings
var fieldMappingCache = &sync.Map{}
// fieldMapping 字段映射信息
type fieldMapping struct {
fromIndex []int // 源字段索引路径
toIndex int // 目标字段索引
}
// getFieldMappings 获取字段映射缓存
func getFieldMappings(fromType, toType reflect.Type) ([]fieldMapping, bool) {
key := cacheKey(fromType, toType)
if cached, ok := fieldMappingCache.Load(key); ok {
return cached.([]fieldMapping), true
}
return nil, false
}
// cacheKey 生成缓存键
func cacheKey(fromType, toType reflect.Type) string {
return fromType.String() + "->" + toType.String()
}
// buildFieldMappings 构建字段映射关系
func buildFieldMappings(fromType, toType reflect.Type) []fieldMapping {
mappings := []fieldMapping{}
for i := 0; i < fromType.NumField(); i++ {
fromField := fromType.Field(i)
// 尝试通过 mapper tag 或字段名找到对应字段
fieldName := fromField.Name
toField, found := toType.FieldByName(fieldName)
if !found {
// 尝试通过 mapper tag 查找
if tag := fromField.Tag.Get("mapper"); tag != "" {
if f, ok := toType.FieldByName(tag); ok {
toField = f
found = true
}
}
}
if found && fromField.Type == toField.Type {
mappings = append(mappings, fieldMapping{
fromIndex: []int{i},
toIndex: toField.Index[0],
})
}
}
// 存入缓存
key := cacheKey(fromType, toType)
fieldMappingCache.Store(key, mappings)
return mappings
}
// ============ 函数式泛型 Mapper (优化版) ============
// MapDirect 同构/异构映射,直接返回结果
// 使用示例: dto := mapper.MapDirect[User, UserDTO](user)
func MapDirect[From, To any](from From) To {
var result To
fromVal := reflect.ValueOf(from)
if !fromVal.IsValid() {
return result
}
// 处理指针类型
if fromVal.Kind() == reflect.Ptr {
if fromVal.IsNil() {
return result
}
fromVal = fromVal.Elem()
}
// 获取类型信息
fromType := fromVal.Type()
toType := reflect.TypeOf(result)
if toType.Kind() != reflect.Struct {
return result
}
// 尝试从缓存获取映射关系
mappings, ok := getFieldMappings(fromType, toType)
if !ok {
mappings = buildFieldMappings(fromType, toType)
}
// 创建目标值
toVal := reflect.New(toType).Elem()
// 执行映射
for _, m := range mappings {
if len(m.fromIndex) > 0 {
fromFieldVal := fromVal.FieldByIndex(m.fromIndex)
toFieldVal := toVal.Field(m.toIndex)
if toFieldVal.CanSet() {
toFieldVal.Set(fromFieldVal)
}
}
}
return toVal.Interface().(To)
}
// MapDirectPtr 指针版本
// 使用示例: dto := mapper.MapDirectPtr[User, UserDTO](&user)
func MapDirectPtr[From, To any](from *From) *To {
if from == nil {
return nil
}
result := MapDirect[From, To](*from)
return &result
}
// MapDirectSlice 批量映射
// 使用示例: dtos := mapper.MapDirectSlice[User, UserDTO](users)
func MapDirectSlice[From, To any](from []From) []To {
if from == nil {
return nil
}
// 尝试预获取映射关系以优化批量操作
fromType := reflect.TypeOf((*From)(nil)).Elem()
toType := reflect.TypeOf((*To)(nil)).Elem()
_, hasCache := getFieldMappings(fromType, toType)
if !hasCache {
buildFieldMappings(fromType, toType)
}
result := make([]To, len(from))
for i, v := range from {
result[i] = MapDirect[From, To](v)
}
return result
}
// MapDirectPtrSlice 指针切片映射
// 使用示例: dtos := mapper.MapDirectPtrSlice[User, UserDTO](&users)
func MapDirectPtrSlice[From, To any](from []*From) []*To {
if from == nil {
return nil
}
result := make([]*To, len(from))
for i, v := range from {
if v != nil {
t := MapDirect[From, To](*v)
result[i] = &t
}
}
return result
}
// ============ 错误处理函数 (优化版) ============
// SafeMapDirect 安全映射,忽略错误
// 使用示例: dto := mapper.SafeMapDirect[User, UserDTO](user)
func SafeMapDirect[From, To any](from From) (To, error) {
var result To
fromVal := reflect.ValueOf(from)
if !fromVal.IsValid() {
return result, errors.New("invalid from value")
}
// 处理指针类型
if fromVal.Kind() == reflect.Ptr {
if fromVal.IsNil() {
return result, errors.New("from is nil pointer")
}
fromVal = fromVal.Elem()
}
// 获取类型信息
fromType := fromVal.Type()
toType := reflect.TypeOf(result)
if toType.Kind() != reflect.Struct {
return result, nil
}
// 尝试从缓存获取映射关系
mappings, ok := getFieldMappings(fromType, toType)
if !ok {
mappings = buildFieldMappings(fromType, toType)
}
// 创建目标值
toVal := reflect.New(toType).Elem()
// 执行映射
for _, m := range mappings {
if len(m.fromIndex) > 0 {
fromFieldVal := fromVal.FieldByIndex(m.fromIndex)
toFieldVal := toVal.Field(m.toIndex)
if toFieldVal.CanSet() {
toFieldVal.Set(fromFieldVal)
}
}
}
return toVal.Interface().(To), nil
}
// SafeMapDirectSlice 安全批量映射
// 使用示例: dtos, err := mapper.SafeMapDirectSlice[User, UserDTO](users)
func SafeMapDirectSlice[From, To any](from []From) ([]To, error) {
if from == nil {
return nil, nil
}
result := make([]To, len(from))
for i, v := range from {
r, err := SafeMapDirect[From, To](v)
if err != nil {
return nil, errors.New("map slice failed at index " + string(rune(i+'0')))
}
result[i] = r
}
return result, nil
}
// ClearFieldMappingCache 清除字段映射缓存
// 用于在需要重新构建映射关系时调用
func ClearFieldMappingCache() {
fieldMappingCache = &sync.Map{}
}