-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
49 lines (43 loc) · 1.23 KB
/
utils.go
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
package data
import (
"go/ast"
"reflect"
"github.com/farseer-go/fs/snc"
"gorm.io/gorm/schema"
)
// ToMap PO实体转map
func ToMap(entity any) map[string]any {
dic := make(map[string]any)
dicValue := reflect.ValueOf(dic)
fsVal := reflect.Indirect(reflect.ValueOf(entity))
namingStrategy := schema.NamingStrategy{IdentifierMaxLength: 64}
// 遍历字段
for i := 0; i < fsVal.NumField(); i++ {
var fieldName string
// 取出当前字段
if field := fsVal.Type().Field(i); ast.IsExported(field.Name) {
fieldName = field.Name
// 取出gorm标签
fieldTags := schema.ParseTagSetting(field.Tag.Get("gorm"), ";")
// 取出Column标签
if colName, existsColumn := fieldTags["COLUMN"]; existsColumn {
fieldName = colName
} else {
fieldName = namingStrategy.ColumnName("", field.Name)
}
// 取出json标签
_, isJsonField := fieldTags["JSON"]
if !isJsonField {
jsonTag, existsJsonTag := fieldTags["SERIALIZER"]
isJsonField = existsJsonTag && jsonTag == "json"
}
itemValue := fsVal.Field(i)
if isJsonField {
marshal, _ := snc.Marshal(itemValue.Interface())
itemValue = reflect.ValueOf(marshal)
}
dicValue.SetMapIndex(reflect.ValueOf(fieldName), itemValue)
}
}
return dic
}