/
validator.go
91 lines (76 loc) · 1.61 KB
/
validator.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
package cli
import (
"net/http"
"net/url"
"strconv"
"strings"
"github.com/pkg/errors"
)
// Validator handle
type Validator struct{}
// URL validator
func (v Validator) URL(u string) error {
pu, err := url.ParseRequestURI(u)
if err != nil {
return errors.Wrapf(
err,
"Invalid value '%s' for flag --url",
u,
)
}
// Empty Host
if pu.Host == "" {
return errors.Errorf("Invalid value '%s' for flag --url, no host", u)
}
// Invalid Scheme
if !strings.HasPrefix(pu.Scheme, "http") && !strings.HasPrefix(pu.Scheme, "https") {
return errors.Errorf("Invalid value '%s' for flag --url, url should start with http/https not %s", pu.Host, pu.Scheme)
}
return nil
}
// HTTPMethod validator
func (v Validator) HTTPMethod(method string) error {
httpMethods := map[string]struct{}{
http.MethodGet: {},
http.MethodPost: {},
http.MethodPut: {},
http.MethodPatch: {},
http.MethodDelete: {},
}
_, ok := httpMethods[method]
if !ok {
return errors.Errorf(
"Invalid value '%s' for flag -method, valid values are %s",
method,
mapKeys(httpMethods),
)
}
return nil
}
// VerboseLevel validator
func (v Validator) VerboseLevel(level int) error {
verboseLevels := map[string]struct{}{
"1": {},
"2": {},
"3": {},
"4": {},
"5": {},
}
_, ok := verboseLevels[strconv.Itoa(level)]
if !ok {
return errors.Errorf(
"Invalid value '%d' for flag -verbose, valid values are %s",
level,
mapKeys(verboseLevels),
)
}
return nil
}
func mapKeys(m map[string]struct{}) []string {
// nolint:prealloc
var keys []string
for k := range m {
keys = append(keys, k)
}
return keys
}