Home > Mobile >  How to use yaml.Validate in cuelang for yaml validation?
How to use yaml.Validate in cuelang for yaml validation?

Time:07-11

/cuelang.org/go/yaml.go
func Validate(b []byte, v cue.Value) error {
   _, err := pkgyaml.Validate(b, v)
   return err
}

There isn't any sample code to tell me how to use this API, I need some examples to understand how to use it.

CodePudding user response:

I figured it out. First we need a cue file:

// demo.cue
min: number
max: number & >min

And then:

// valid_test.go
package demo

import (
    "cuelang.org/go/cue/cuecontext"
    "cuelang.org/go/encoding/yaml"
    "fmt"
    "io/ioutil"
    "strings"
    "testing"
)

const Yaml = `
min: 10
max: 5
`

func TestValidate(t *testing.T) {
    r := strings.NewReader(Yaml)
    b, _ := ioutil.ReadAll(r)
    cue, _ := ioutil.ReadFile("demo.cue")

    // Cue API for Go
    c := cuecontext.New()
    v := c.CompileBytes(cue)
    err := yaml.Validate(b, v)

    fmt.Println(err) // max: invalid value 5 (out of bound >10)
}
  • Related