forked from garetht/amanar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschema_validator.go
65 lines (50 loc) · 1.67 KB
/
schema_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
package amanar
import (
"fmt"
"github.com/xeipuuv/gojsonschema"
)
func ValidateConfiguration(documentLoader gojsonschema.JSONLoader) (err error, re []gojsonschema.ResultError) {
schema, err := Asset("amanar_config_schema.json")
if err != nil {
return fmt.Errorf("could not load schema assets: %w", err), nil
}
// We validate the Go document in order to be able to use gojsonschema to validate YAML
schemaLoader := gojsonschema.NewBytesLoader(schema)
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return fmt.Errorf("was not able to run validation on schema: %w", err), nil
}
if !result.Valid() {
re = result.Errors()
return
}
return
}
type SchemaValidator interface {
loader() gojsonschema.JSONLoader
Validate() (err error, re []gojsonschema.ResultError)
}
type StructSchemaValidator struct {
goStruct *Amanar
}
func (s StructSchemaValidator) loader() gojsonschema.JSONLoader {
return gojsonschema.NewGoLoader(s.goStruct)
}
func (s StructSchemaValidator) Validate() (err error, re []gojsonschema.ResultError) {
return ValidateConfiguration(s.loader())
}
func NewStructSchemaValidator(goStruct *Amanar) *StructSchemaValidator {
return &StructSchemaValidator{goStruct: goStruct}
}
type JsonBytesSchemaValidator struct {
jsonBytes []byte
}
func (j JsonBytesSchemaValidator) loader() gojsonschema.JSONLoader {
return gojsonschema.NewBytesLoader(j.jsonBytes)
}
func (j JsonBytesSchemaValidator) Validate() (err error, re []gojsonschema.ResultError) {
return ValidateConfiguration(j.loader())
}
func NewJsonBytesSchemaValidator(jsonBytes []byte) *JsonBytesSchemaValidator {
return &JsonBytesSchemaValidator{jsonBytes: jsonBytes}
}