forked from s-mang/test2doc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parameter.go
95 lines (78 loc) · 1.6 KB
/
parameter.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
package doc
import (
"fmt"
"regexp"
"text/template"
)
type ParameterType int
const (
Number ParameterType = iota
String
Boolean
)
const (
numberRe = `^[0-9\.]+$`
boolRe = `^(?:[tT][rR][uU][eE]|[fF][aA][lL][sS][eE])$`
)
var (
parameterTmpl *template.Template
parameterFmt = ` + {{.Name}}: {{.Value.Quote}} ({{.Type.String}}){{with .Description}} - {{.}}{{end}}`
)
func init() {
parameterTmpl = template.Must(template.New("parameter").Parse(parameterFmt))
}
type Parameter struct {
Name string
Description string
Value ParameterValue
Type ParameterType
IsRequired bool
// TODO:
// DefaultValue
}
func MakeParameter(key, val string) Parameter {
return Parameter{
Name: key,
Value: ParameterValue(val),
Type: paramType(val),
IsRequired: true, // assume anything in route URL is required
// query params are a different story
}
}
func (p *Parameter) Render() string {
return render(parameterTmpl, p)
}
type ParameterValue string
func (val ParameterValue) Quote() (qval string) {
if len(val) > 0 {
qval = fmt.Sprintf("`%s`", string(val))
}
return
}
func paramType(val string) ParameterType {
if isBool(val) {
return Boolean
} else if isNumber(val) {
return Number
} else {
return String
}
}
func isBool(str string) bool {
re := regexp.MustCompile(boolRe)
return re.MatchString(str)
}
func isNumber(str string) bool {
re := regexp.MustCompile(numberRe)
return re.MatchString(str)
}
func (pt ParameterType) String() string {
switch pt {
case Number:
return "number"
case Boolean:
return "boolean"
default:
return "string"
}
}