-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
86 lines (69 loc) · 1.61 KB
/
parser.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
package textra
import (
"reflect"
"regexp"
"strings"
)
var tagRegexp = regexp.MustCompile(`(\w+:\"[^\"]+\")`)
func parseTags(tag reflect.StructTag) Tags {
tags := tagRegexp.FindAllString(string(tag), -1)
parsed := make(Tags, 0, len(tags))
for _, tagStr := range tags {
parsed = append(parsed, parseTag(tagStr))
}
return parsed
}
func parseTag(tagStr string) Tag {
split := strings.Split(tagStr, ":")
v := strings.Trim(split[1], "\"")
vs := strings.Split(v, ",")
value := strings.TrimSpace(vs[0])
tag := Tag{
Tag: split[0],
Value: value,
}
if len(vs) > 1 {
tag.Optional = make([]string, 0, len(vs)-1)
for _, opt := range vs[1:] {
tag.Optional = append(tag.Optional, strings.TrimSpace(opt))
}
}
return tag
}
func parseType(typ reflect.Type) string {
switch typ.Kind() {
case reflect.Ptr:
return "*" + typ.Elem().String()
case reflect.Slice:
return "[]" + typ.Elem().String()
case reflect.Struct:
if len(typ.PkgPath()) > 0 {
return typ.PkgPath() + "." + typ.Name()
}
return typ.Kind().String()
case reflect.Map:
return "map[" + typ.Key().String() + "]" + typ.Elem().String()
case reflect.Func:
var args, results string
for i := 0; i < typ.NumIn(); i++ {
args += parseType(typ.In(i))
if i != typ.NumIn()-1 {
args += ", "
}
}
for i := 0; i < typ.NumOut(); i++ {
results += parseType(typ.Out(i))
if i != typ.NumOut()-1 {
results += ", "
}
}
return "func(" + args + ") " + results
case reflect.Interface:
if _, ok := reflect.New(typ).Interface().(*error); ok {
return "error"
}
fallthrough
default:
return typ.Kind().String()
}
}