forked from emicklei/go-restful-openapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproperty_ext.go
104 lines (92 loc) · 2.45 KB
/
property_ext.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
93
94
95
96
97
98
99
100
101
102
103
104
package restfulspec
import (
"reflect"
"strconv"
"strings"
"github.com/go-openapi/spec"
)
func setDescription(prop *spec.Schema, field reflect.StructField) {
if tag := field.Tag.Get("description"); tag != "" {
prop.Description = tag
}
}
func setDefaultValue(prop *spec.Schema, field reflect.StructField) {
if tag := field.Tag.Get("default"); tag != "" {
prop.Default = stringAutoType(tag)
}
}
func setEnumValues(prop *spec.Schema, field reflect.StructField) {
// We use | to separate the enum values. This value is chosen
// since its unlikely to be useful in actual enumeration values.
if tag := field.Tag.Get("enum"); tag != "" {
enums := []interface{}{}
for _, s := range strings.Split(tag, "|") {
enums = append(enums, s)
}
prop.Enum = enums
}
}
func setMaximum(prop *spec.Schema, field reflect.StructField) {
if tag := field.Tag.Get("maximum"); tag != "" {
value, err := strconv.ParseFloat(tag, 64)
if err == nil {
prop.Maximum = &value
}
}
}
func setMinimum(prop *spec.Schema, field reflect.StructField) {
if tag := field.Tag.Get("minimum"); tag != "" {
value, err := strconv.ParseFloat(tag, 64)
if err == nil {
prop.Minimum = &value
}
}
}
func setType(prop *spec.Schema, field reflect.StructField) {
if tag := field.Tag.Get("type"); tag != "" {
// Check if the first two characters of the type tag are
// intended to emulate slice/array behaviour.
//
// If type is intended to be a slice/array then add the
// overriden type to the array item instead of the main property
if len(tag) > 2 && tag[0:2] == "[]" {
pType := "array"
prop.Type = []string{pType}
prop.Items = &spec.SchemaOrArray{
Schema: &spec.Schema{},
}
iType := tag[2:]
prop.Items.Schema.Type = []string{iType}
return
}
prop.Type = []string{tag}
}
}
func setUniqueItems(prop *spec.Schema, field reflect.StructField) {
tag := field.Tag.Get("unique")
switch tag {
case "true":
prop.UniqueItems = true
case "false":
prop.UniqueItems = false
}
}
func setReadOnly(prop *spec.Schema, field reflect.StructField) {
tag := field.Tag.Get("readOnly")
switch tag {
case "true":
prop.ReadOnly = true
case "false":
prop.ReadOnly = false
}
}
func setPropertyMetadata(prop *spec.Schema, field reflect.StructField) {
setDescription(prop, field)
setDefaultValue(prop, field)
setEnumValues(prop, field)
setMinimum(prop, field)
setMaximum(prop, field)
setUniqueItems(prop, field)
setType(prop, field)
setReadOnly(prop, field)
}