-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidate.go
67 lines (54 loc) · 1.41 KB
/
validate.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
package validate
import (
"github.com/op/go-logging"
"net/http"
"reflect"
)
type RuleBook map[string]interface{}
var Log = logging.MustGetLogger("validate")
type ValidationData struct {
data interface{}
}
func Validate(data map[string]interface{}) *ValidationData {
return &ValidationData{data: data}
}
func (v *ValidationData) With(rules RuleBook) (map[string]interface{}, map[string][]error) {
if _, ok := v.data.(*http.Request); ok {
return Request(v.data.(*http.Request), rules)
} else {
return Map(v.data.(map[string]interface{}), rules)
}
}
func sameType(vals ...interface{}) bool {
expectedType := reflect.TypeOf(vals[0]).Kind()
for _, val := range vals {
if expectedType != reflect.TypeOf(val).Kind() {
return false
}
}
return true
}
func Request(given *http.Request, expected RuleBook) (map[string]interface{}, map[string][]error) {
// TODO
return nil, nil
}
func Map(given map[string]interface{}, expected RuleBook) (map[string]interface{}, map[string][]error) {
params := make(map[string]interface{})
paramErrors := make(map[string][]error)
for k, v := range expected {
builder, ok := v.(ruleBuilder)
if ok {
rule := builder.Build()
input, errors := rule.Process(given[k])
if errors != nil {
paramErrors[k] = errors
} else {
params[k] = input
}
}
}
return params, paramErrors
}
func SetLoggingLevel(level logging.Level) {
logging.SetLevel(level, "validate")
}