druzuz321103 2019-06-08 11:46 采纳率: 100%
浏览 233
已采纳

进行YAML解析:必填字段

Summary: I need to parse data in YAML format into golang struct. It there a way (library, attributes) to make some of the fields mandatory, i.e. to make Unmarshal function return the error in case if some field doesn't exist?

Example what is wanted: Unmarshal function in this code should raise an error because input data doesn't contain 'b' field.

package main

import (
    "fmt"
    "gopkg.in/yaml.v2"
)

type TestStruct struct {
    FieldA string `yaml:"a"`
    FieldB string `yaml:"b"`
}

func main() {
    input := []byte(`{a: 1}`)
    var output TestStruct

    _ = yaml.Unmarshal(input, &output)
}
  • 写回答

1条回答 默认 最新

  • dongyu1979 2019-06-08 15:09
    关注

    You can use this library's HasZero method to check wether there are any missing values in a struct. This will return true or false depending wether the struct is completely filled or not. Please see the playground example to get an idea.

    But if you specifically need to tell what field is missing, you need to check wether the value is nil like in the example below.

    package main
    import (
       "fmt"
       "errors"
      "gopkg.in/yaml.v2"
    )
    
    type TestStruct struct {
      FieldA  string `yaml:"a"`
      FieldB  string `yaml:"b"`
    }
    
    func main() {
      input := []byte(`{a: 1}`)
    
      var output TestStruct 
      if err := output.ParseFromFile(input); err != nil {
         fmt.Println(err)
      }
      fmt.Println(output)     
    }
    
    func (output *TestStruct) ParseFromFile(data []byte) error {
    
      if err := yaml.Unmarshal(data, output); err != nil {
        return err
      }
    
      if output.FieldA == "" {
        return errors.New("Blank Field A")
      }
      if output.FieldB == "" {
        return errors.New("Blank Field B")
      }
    
      return nil
    }
    

    Playground example if you need to specifically return an error

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?