【问题标题】:How to use yaml.Validate in cuelang for yaml validation?如何在 cuelang 中使用 yaml.Validate 进行 yaml 验证?
【发布时间】:2022-11-04 05:36:25
【问题描述】:
/cuelang.org/go/yaml.go
func Validate(b []byte, v cue.Value) error {
   _, err := pkgyaml.Validate(b, v)
   return err
}

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

【问题讨论】:

    标签: go yaml cuelang


    【解决方案1】:

    我想到了。首先我们需要一个 cue 文件:

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

    接着:

    // 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)
    }
    

    【讨论】:

      【解决方案2】:

      现在我们如何根据 cue 文件更新 yaml(如默认值和其他约束)?

      【讨论】:

      猜你喜欢
      • 2020-11-19
      • 2023-03-19
      • 1970-01-01
      • 2021-06-14
      • 2011-01-20
      • 2019-06-12
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多