-
Notifications
You must be signed in to change notification settings - Fork 84
/
validator.go
107 lines (89 loc) · 2.14 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package jsonschema
import (
"encoding/json"
"strings"
"github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/xeipuuv/gojsonschema"
)
type validator struct {
schema *gojsonschema.Schema
}
// ValidationResult missing godoc
type ValidationResult struct {
Valid bool
Error error
}
// NewValidatorFromStringSchema missing godoc
func NewValidatorFromStringSchema(jsonSchema string) (*validator, error) {
if jsonSchema == "" {
return &validator{schema: nil}, nil
}
sl := gojsonschema.NewStringLoader(jsonSchema)
schema, err := gojsonschema.NewSchema(sl)
if err != nil {
return nil, err
}
return &validator{
schema: schema,
}, nil
}
// NewValidatorFromRawSchema missing godoc
func NewValidatorFromRawSchema(jsonSchema interface{}) (*validator, error) {
if jsonSchema == nil {
return &validator{}, nil
}
sl := gojsonschema.NewGoLoader(jsonSchema)
schema, err := gojsonschema.NewSchema(sl)
if err != nil {
return nil, err
}
return &validator{
schema: schema,
}, nil
}
// ValidateString missing godoc
func (v *validator) ValidateString(json string) (ValidationResult, error) {
if v.schema == nil {
return ValidationResult{
Valid: true,
Error: nil,
}, nil
}
jsonLoader := gojsonschema.NewStringLoader(json)
result, err := v.schema.Validate(jsonLoader)
if err != nil {
return ValidationResult{}, err
}
var validationError *multierror.Error
for _, e := range result.Errors() {
validationError = multierror.Append(validationError, errors.New(e.String()))
}
if validationError != nil {
validationError.ErrorFormat = func(i []error) string {
var s []string
for _, v := range i {
s = append(s, v.Error())
}
return strings.Join(s, ", ")
}
}
return ValidationResult{
Valid: result.Valid(),
Error: validationError.ErrorOrNil(),
}, nil
}
// ValidateRaw missing godoc
func (v *validator) ValidateRaw(value interface{}) (ValidationResult, error) {
if v.schema == nil {
return ValidationResult{
Valid: true,
Error: nil,
}, nil
}
valueMarshalled, err := json.Marshal(value)
if err != nil {
return ValidationResult{}, err
}
return v.ValidateString(string(valueMarshalled))
}