How to validate data against schema in v0.4.0 in Go #1030
-
Hello, I wrote a couple of definition in CUE, for example:
I can use Is there a straightforward way to do it? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
Here is the solution: package main
import (
"log"
"cuelang.org/go/cue"
"cuelang.org/go/cue/cuecontext"
"cuelang.org/go/cue/load"
)
func main() {
ctx := cuecontext.New()
binst := load.Instances([]string{"definitions.cue", "testdata/sample.cue"}, nil)
insts, err := ctx.BuildInstances(binst)
if err != nil {
log.Fatal(err)
}
if len(insts) != 1 {
log.Fatal("more than one instance")
}
v := insts[0]
opts := []cue.Option{
cue.Attributes(true),
cue.Definitions(true),
cue.Hidden(true),
}
err = v.Validate(opts...)
if err != nil {
log.Fatal(err)
}
} |
Beta Was this translation helpful? Give feedback.
-
I add one more question: Consider the following data:
I can validate the file without explicitly loading the definitions: ...
binst := load.Instances([]string{ "testdata/sample.cue"}, nil)
... I wonder now if there is a way to load the "definitions" in a context, a runtime, or whatever, so I can validate the data on the fly in a webservice for example? edit I tried with JSON which would do what I am trying to achieve: package main
import (
"io/ioutil"
"log"
"cuelang.org/go/cue/cuecontext"
"cuelang.org/go/cue/load"
"cuelang.org/go/encoding/json"
)
func main() {
ctx := cuecontext.New()
binst := load.Instances([]string{"definitions.cue"}, nil)
insts, err := ctx.BuildInstances(binst)
if err != nil {
log.Fatal(err)
}
if len(insts) != 1 {
log.Fatal("more than one instance")
}
v := insts[0]
b, err := ioutil.ReadFile("testdata/bad.json")
if err != nil {
log.Fatal(err)
}
err = json.Validate(b, v)
if err == nil {
log.Fatal(err)
}
} and bad.json is: {
"message": {
"envelop": {
"topic": "net.mycompany.sample1.topic:1234",
"subject": "123e4567-e89b-12d3-a456-426614174000",
"type": "net.mycompany.sample1:c",
"version": "v1.0.0"
},
"data": {
"weight": 250
}
}
} This should fail, but it does not :( |
Beta Was this translation helpful? Give feedback.
-
This discussion has been migrated to cue-lang/cue#1030. For more details about CUE's migration to a new home, please see cue-lang/cue#1078. |
Beta Was this translation helpful? Give feedback.
Here is the solution: