-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmeta.go
74 lines (56 loc) · 1.36 KB
/
meta.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
package crud
import (
"fmt"
"reflect"
"strings"
)
type fieldMeta struct {
GoName string
SqlName string
Unix bool
}
/*
sqlToGoFields extracts the data contained within the "crud" struct tags.
The "crud" struct tags contain the name of the SQL column which stores the
tagged field. sqlToGoFields returns a mapping from SQL column name to Go
field name.
*/
func sqlToGoFields(ty reflect.Type) (map[string]fieldMeta, error) {
ty = indirectT(ty)
if ty.Kind() != reflect.Struct {
return nil, fmt.Errorf("sqlToGoFields: type %s is not a struct", ty.Name())
}
fieldMap := make(map[string]fieldMeta)
for i := 0 ; i < ty.NumField() ; i += 1 {
field := ty.Field(i)
tag := field.Tag.Get("crud")
if tag != "" {
tagPieces := strings.Split(tag, ",")
meta := fieldMeta{
SqlName: tagPieces[0],
GoName: field.Name,
}
for idx := 1; idx < len(tagPieces); idx += 1 {
if tagPieces[idx] == "unix" {
meta.Unix = true
}
}
fieldMap[meta.SqlName] = meta
}
}
return fieldMap, nil
}
/* indirectT returns the passed type, recursively indirected. */
func indirectT(ty reflect.Type) reflect.Type {
for ty.Kind() == reflect.Ptr {
ty = ty.Elem()
}
return ty
}
/* indirectV returns the passed type, recursively indirected. */
func indirectV(val reflect.Value) reflect.Value {
for val.Kind() == reflect.Ptr {
val = val.Elem()
}
return val
}