-
Notifications
You must be signed in to change notification settings - Fork 3
/
parse.go
68 lines (59 loc) · 1.35 KB
/
parse.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
package openapi
import (
"reflect"
"strings"
)
// ParseParams parses parameters from a struct using the given
// tag to derive its name.
func ParseParams(obj any, tag string) []Parameter {
if tag == "" {
tag = "json"
}
t := reflect.TypeOf(obj)
if t.Kind() == reflect.Pointer {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil
}
docable, isDocable := obj.(interface {
Docs() map[string]string
})
var params []Parameter
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
switch f.Type.Kind() {
case reflect.Interface, reflect.Struct, reflect.Pointer:
continue
}
tagStr := f.Tag.Get(tag)
if tagStr == "" || tagStr == "-" {
continue
}
tagName := strings.SplitN(tagStr, ",", 2)[0]
if tagName == "" {
continue
}
var desc string
if isDocable {
desc = docable.Docs()[tagName]
}
params = append(params, QueryParameterWithType(tagName, desc, typeToJSON(f.Type.String())))
}
return params
}
func typeToJSON(typ string) string {
switch typ {
case "bool", "*bool":
return "boolean"
case "uint8", "*uint8", "int", "*int", "int32", "*int32", "int64", "*int64", "uint32", "*uint32", "uint64", "*uint64":
return "integer"
case "float64", "*float64", "float32", "*float32":
return "number"
case "byte", "*byte":
fallthrough
case "map[string]string", "*map[string]string":
return "string"
}
return typ
}