-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathvalidator.go
65 lines (56 loc) · 1.28 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
package plugin
import (
"errors"
"gopkg.in/vinxi/vinxi.v0/config"
)
// getField is used to find and retrieve the param Field configuration.
func getField(name string, params Params) (Field, bool) {
for _, field := range params {
if field.Name == name {
return field, true
}
}
return Field{}, false
}
// Validate is used to validates plugin params
// and report the proper param specific error.
func Validate(params Params, opts config.Config) error {
// Set defaults params
for _, param := range params {
// Set defaults
if param.Default != nil && !opts.Exists(param.Name) {
opts.Set(param.Name, param.Default)
}
// Validate mandatory params
if param.Mandatory && !opts.Exists(param.Name) {
return errors.New("Missing required param: " + param.Name)
}
}
// Validate params
for name, value := range opts {
field, exists := getField(name, params)
if !exists {
continue
}
// Cast type to verify type contract
var kind string
switch value.(type) {
case string:
kind = "string"
case int:
kind = "int"
case bool:
kind = "bool"
}
if kind != field.Type {
return errors.New("Invalid type for param: " + name)
}
if field.Validator != nil {
err := field.Validator(value, opts)
if err != nil {
return err
}
}
}
return nil
}