-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil_common.go
90 lines (77 loc) · 2.2 KB
/
util_common.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
package ssql
import (
"encoding/base64"
"reflect"
"strings"
"github.com/samber/lo"
)
func base64Encode(input string) string {
return base64.StdEncoding.EncodeToString([]byte(input))
}
func base64Decode(input string) (string, error) {
str, err := base64.StdEncoding.DecodeString(input)
if err != nil {
return "", nil
}
return string(str), nil
}
func reverse[T any](args *[]T) *[]T {
*args = lo.Reverse(*args)
return args
}
func popArray[T any](slice *[]T) *[]T {
if slice == nil {
return nil
}
if len(*slice) < 1 {
return slice
}
*slice = append((*slice)[:len(*slice)-1], (*slice)[len(*slice):]...)
return slice
}
var mappingCache = map[interface{}][]TagMappings{}
func getMappingCacheKey(t *reflect.Type, tags *[]string) string {
return (*t).PkgPath() + ":" + (*t).Name() + ":" + strings.Join(*tags, ",")
}
func ExtractStructMappings(tags []string, s interface{}) (TagMappings, TagMappings) {
t, _ := getStructType(s)
cacheKey := getMappingCacheKey(t, &tags)
if mappingCache[cacheKey] != nil && len(mappingCache[cacheKey]) > 1 {
return mappingCache[cacheKey][0], mappingCache[cacheKey][1]
}
mappingsByFields := TagMappings{}
mappingsByTags := TagMappings{}
tags = append(tags, "relation")
for i := 0; i < (*t).NumField(); i++ {
field := (*t).Field(i)
for _, tag := range tags {
col := field.Tag.Get(tag)
if mappingsByFields[tag] == nil {
mappingsByFields[tag] = make(map[string]string)
}
if mappingsByTags[tag] == nil {
mappingsByTags[tag] = make(map[string]string)
}
if col != "" {
mappingsByFields[tag][field.Name] = strings.Split(col, ",")[0]
mappingsByTags[tag][strings.Split(col, ",")[0]] = field.Name
}
}
}
mappingCache[cacheKey] = []TagMappings{mappingsByTags, mappingsByFields}
return mappingsByTags, mappingsByFields
}
type TagMappings map[string]map[string]string // [tagType][structField]tagValue.
func (mappings TagMappings) GetTag(tag, field string) string {
if tag == "" || field == "" || mappings[tag] == nil {
return ""
}
return mappings[tag][field]
}
func getStructType(s interface{}) (*reflect.Type, string) {
if t := reflect.TypeOf(s); t.Kind() == reflect.Ptr {
return &t, "*" + t.Elem().Name()
} else {
return &t, t.Name()
}
}