forked from santhosh-tekuri/jsonschema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_extension_test.go
77 lines (64 loc) · 1.56 KB
/
example_extension_test.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
package jsonschema_test
import (
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"github.com/santhosh-tekuri/jsonschema/v5"
)
var powerOfMeta = jsonschema.MustCompileString("powerOf.json", `{
"properties" : {
"powerOf": {
"type": "integer",
"exclusiveMinimum": 0
}
}
}`)
type powerOfCompiler struct{}
func (powerOfCompiler) Compile(ctx jsonschema.CompilerContext, m map[string]interface{}) (jsonschema.ExtSchema, error) {
if pow, ok := m["powerOf"]; ok {
n, err := pow.(json.Number).Int64()
return powerOfSchema(n), err
}
// nothing to compile, return nil
return nil, nil
}
type powerOfSchema int64
func (s powerOfSchema) Validate(ctx jsonschema.ValidationContext, v interface{}) error {
switch v.(type) {
case json.Number, float32, float64, int, int8, int32, int64, uint, uint8, uint32, uint64:
pow := int64(s)
n, _ := strconv.ParseInt(fmt.Sprint(v), 10, 64)
for n%pow == 0 {
n = n / pow
}
if n != 1 {
return ctx.Error("powerOf", "%v not powerOf %v", v, pow)
}
return nil
default:
return nil
}
}
func Example_extension() {
c := jsonschema.NewCompiler()
c.RegisterExtension("powerOf", powerOfMeta, powerOfCompiler{})
schema := `{"powerOf": 10}`
instance := `100`
if err := c.AddResource("schema.json", strings.NewReader(schema)); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("schema.json")
if err != nil {
log.Fatalf("%#v", err)
}
var v interface{}
if err := json.Unmarshal([]byte(instance), &v); err != nil {
log.Fatal(err)
}
if err = sch.Validate(v); err != nil {
log.Fatalf("%#v", err)
}
// Output:
}