-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
92 lines (79 loc) · 1.82 KB
/
util.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
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
package dal
import (
"bytes"
"database/sql/driver"
"reflect"
"strings"
"unicode"
)
func camelCaseToSnakeCase(name string) string {
buf := new(bytes.Buffer)
runes := []rune(name)
for i := 0; i < len(runes); i++ {
buf.WriteRune(unicode.ToLower(runes[i]))
if i != len(runes)-1 && unicode.IsUpper(runes[i+1]) &&
(unicode.IsLower(runes[i]) || unicode.IsDigit(runes[i]) ||
(i != len(runes)-2 && unicode.IsLower(runes[i+2]))) {
buf.WriteRune('_')
}
}
return buf.String()
}
func structMap(value reflect.Value) map[string]reflect.Value {
m := make(map[string]reflect.Value)
structValue(m, value)
return m
}
var (
typeValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem()
)
func structValue(m map[string]reflect.Value, value reflect.Value) {
if value.Type().Implements(typeValuer) {
return
}
switch value.Kind() {
case reflect.Ptr:
if value.IsNil() {
return
}
structValue(m, value.Elem())
case reflect.Struct:
t := value.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if field.PkgPath != "" && !field.Anonymous {
// unexported
continue
}
tag := field.Tag.Get("db")
tags := strings.Split(tag, ",")
tagName := ""
for _, t := range tags {
if strings.Contains(t, "=") {
split := strings.Split(t, "=")
split[0] = strings.TrimSpace(split[0])
split[1] = strings.TrimSpace(split[1])
if strings.ToLower(split[0]) == "name" {
tagName = split[1]
}
}
}
if tagName == "" {
tagName = strings.TrimSpace(tags[0])
}
if tagName == "-" {
// ignore
continue
}
if tagName == "" {
// no tag, but we can record the field name
tagName = camelCaseToSnakeCase(field.Name)
}
fieldValue := value.Field(i)
if _, ok := m[tag]; !ok {
m[tagName] = fieldValue
}
structValue(m, fieldValue)
}
}
}