-
I'm trying to validate an ad-hoc struct but it never fails the validation: package main
import (
"fmt"
"cuelang.org/go/cue/cuecontext"
"cuelang.org/go/cue/errors"
)
type Val struct {
I int
S string
b bool
}
func main() {
c := cuecontext.New()
s := c.CompileString(`
#schema: {
i: string
s: string
}
`)
if s.Err() != nil {
fmt.Printf("Compile Error:\n%s\n", errors.Details(s.Err(), nil))
return
}
v := c.Encode(Val{
I: 1,
S: "hello",
b: true,
})
if v.Err() != nil {
fmt.Printf("Encode Error:\n%s\n", errors.Details(v.Err(), nil))
return
}
u := s.Unify(v)
if u.Err() != nil {
fmt.Printf("Unify Error:\n%s\n", errors.Details(u.Err(), nil))
return
}
err := u.Validate()
if err != nil {
fmt.Printf("Validate Error:\n%s\n", errors.Details(err, nil))
return
}
fmt.Printf("%#v\n", u)
} This passes validation, despite I not being a string:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
You were very close! I've presented your code as The
This gives the output:
|
Beta Was this translation helpful? Give feedback.
You were very close! I've presented your code as
main1.go
below and the fixed versions asmain2.go
.The
CompileString()
call you had returned a struct value that has a field named#schema
. You you were unifying and validating your encoded value against that struct value, which is open. Hence it passed. Instead, you need to choose the#schema
value, and unify and validate against that, which is what I do inmain2.go
. You will also notice that I have ensured the field names match, using thejson
field tag.