1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package yaml_loader
- import (
- "bytes"
- "errors"
- "fmt"
- "gopkg.in/yaml.v3"
- "io"
- "os"
- "reflect"
- )
- // LoadYamlFile 加载YAML文件,一个文件中可以有多个YAML对象
- // 参数:
- // yamlFilePath: YAML文件路径
- // retObjects: 用来接收YAML对象的指针或者map的slice
- // 返回值:
- // 错误
- func LoadYamlFile(yamlFilePath string, retObjects *[]any) error {
- yamlFile, err := os.Open(yamlFilePath)
- if err != nil {
- return err
- }
- defer func(yamlFile *os.File) {
- err := yamlFile.Close()
- if err != nil {
- fmt.Println(err)
- }
- }(yamlFile)
- return loadYaml(yamlFile, retObjects)
- }
- // LoadYamlBytes 加载YAML文件字节,一个文件中可以有多个YAML对象
- // 参数:
- // yamlBytes: YAML文件的字节
- // retObjects: 用来接收YAML对象的指针或者map的slice
- // 返回值:
- // 错误
- func LoadYamlBytes(yamlBytes []byte, retObjects *[]any) error {
- return loadYaml(bytes.NewReader(yamlBytes), retObjects)
- }
- func loadYaml(r io.Reader, retObjects *[]any) error {
- decoder := yaml.NewDecoder(r)
- for i := 0; i < len(*retObjects); i++ {
- retObject := (*retObjects)[i]
- retObjectType := reflect.TypeOf(retObject)
- if retObjectType.Kind() != reflect.Ptr && retObjectType.Kind() != reflect.Map {
- return errors.New("返回对象slice需要指针或者map")
- }
- err := decoder.Decode(retObject)
- if err != nil {
- if err == io.EOF {
- break
- }
- return err
- }
- }
- return nil
- }
|