如何在 Cuelang 中使用 yaml.Validate 进行 YAML 验证?

huangapple go评论115阅读模式
英文:

How to use yaml.Validate in cuelang for yaml validation?

问题

以下是要翻译的内容:

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

没有任何示例代码告诉我如何使用这个API,我需要一些示例来了解如何使用它。

英文:
  1. /cuelang.org/go/yaml.go
  2. func Validate(b []byte, v cue.Value) error {
  3. _, err := pkgyaml.Validate(b, v)
  4. return err
  5. }

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

答案1

得分: 1

我明白了。首先,我们需要一个cue文件:

  1. // demo.cue
  2. min: number
  3. max: number & >min

然后是:

  1. // valid_test.go
  2. package demo
  3. import (
  4. "cuelang.org/go/cue/cuecontext"
  5. "cuelang.org/go/encoding/yaml"
  6. "fmt"
  7. "io/ioutil"
  8. "strings"
  9. "testing"
  10. )
  11. const Yaml = `
  12. min: 10
  13. max: 5
  14. `
  15. func TestValidate(t *testing.T) {
  16. r := strings.NewReader(Yaml)
  17. b, _ := ioutil.ReadAll(r)
  18. cue, _ := ioutil.ReadFile("demo.cue")
  19. // Cue API for Go
  20. c := cuecontext.New()
  21. v := c.CompileBytes(cue)
  22. err := yaml.Validate(b, v)
  23. fmt.Println(err) // max: invalid value 5 (out of bound >10)
  24. }
英文:

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

  1. // demo.cue
  2. min: number
  3. max: number & >min

And then:

  1. // valid_test.go
  2. package demo
  3. import (
  4. "cuelang.org/go/cue/cuecontext"
  5. "cuelang.org/go/encoding/yaml"
  6. "fmt"
  7. "io/ioutil"
  8. "strings"
  9. "testing"
  10. )
  11. const Yaml = `
  12. min: 10
  13. max: 5
  14. `
  15. func TestValidate(t *testing.T) {
  16. r := strings.NewReader(Yaml)
  17. b, _ := ioutil.ReadAll(r)
  18. cue, _ := ioutil.ReadFile("demo.cue")
  19. // Cue API for Go
  20. c := cuecontext.New()
  21. v := c.CompileBytes(cue)
  22. err := yaml.Validate(b, v)
  23. fmt.Println(err) // max: invalid value 5 (out of bound >10)
  24. }

huangapple
  • 本文由 发表于 2022年7月8日 01:24:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/72901997.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定