/
type_jsonschema.go
62 lines (51 loc) · 1.14 KB
/
type_jsonschema.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
package args
import (
"encoding/json"
"fmt"
"strings"
"github.com/spyzhov/safe"
"github.com/xeipuuv/gojsonschema"
)
type JSONSchema string
func (a *JSONSchema) Validate() error {
if a == nil {
return nil
}
if !json.Valid([]byte(a.value())) {
return fmt.Errorf("JSON is invalid")
}
return nil
}
func (a *JSONSchema) Match(value []byte) error {
if a == nil {
return nil
}
return a.match(gojsonschema.NewBytesLoader(value))
}
func (a *JSONSchema) MatchString(value string) error {
if a == nil {
return nil
}
return a.match(gojsonschema.NewStringLoader(value))
}
func (a *JSONSchema) match(documentLoader gojsonschema.JSONLoader) error {
schemaLoader := gojsonschema.NewStringLoader(a.value())
result, err := gojsonschema.Validate(schemaLoader, documentLoader)
if err != nil {
return safe.Wrap(err, "JSONSchema")
}
if !result.Valid() {
messages := make([]string, 0)
for _, desc := range result.Errors() {
messages = append(messages, desc.String())
}
return fmt.Errorf("JSONSchema: %s", strings.Join(messages, "\n"))
}
return nil
}
func (a *JSONSchema) value() string {
if a == nil {
return ""
}
return string(*a)
}