Golang validate a yaml structure

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

Golang validate a yaml structure

问题

我是你的中文翻译助手,以下是你要翻译的内容:

我是一个golang的新手。我正在尝试验证一个yaml结构。

prof:
  res:
  - ed:
      app:
        conf:

为此,我使用ioutil读取了yaml文件,然后将其转换为map[string]interface{}。我尝试了以下两种方法:1)循环遍历map接口;2)将其转换为json字符串,然后进行循环遍历,但是都没有成功。

任何帮助将不胜感激。谢谢!

yfile, err1 := ioutil.ReadFile("C:/Users/212764682/user.yaml")
data := make(map[string]interface{})
err := yaml.Unmarshal(yfile, &data)

尝试像这样进行迭代:

for key, value := range data {
		if key == "prof" {
			for key2, value2 := range value.(map[string]interface{}) {
				if key2 == "res" {
					for key3, value3 := range value2.(map[string]interface{}) {

						if key3 == "ed" {
							for key4, value4 := range value3.(map[string]interface{}) {
								if key4 == "app" {
									for key5 := range value4.(map[string]interface{}) {
										if key5 == "conf" {
											fmt.Println("valid format")

										}
									}
								}
							}
						}
					}
				}

			}

		}
	}
英文:

Im a newbie in golang. I am trying to validate a yaml structure

prof:
  res:
  - ed:
      app:
        conf:

For that i have read the yaml file using ioutil, then converted it to map string interface. I tried 1) looping over map interface 2) converting it to json string using marshal and then looping but couldn't achieve it.

Any help will be appreciated. Thanks

yfile, err1 := ioutil.ReadFile("C:/Users/212764682/user.yaml")
data := make(map[string]interface{})
err := yaml.Unmarshal(yfile, &data)

Tried iterating like this

for key, value := range data {
		if key == "prof" {
			for key2, value2 := range value.(map[string]interface{}) {
				if key2 == "res" {
					for key3, value3 := range value2.(map[string]interface{}) {

						if key3 == "ed" {
							for key4, value4 := range value3.(map[string]interface{}) {
								if key4 == "app" {
									for key5 := range value4.(map[string]interface{}) {
										if key5 == "conf" {
											fmt.Println("valid format")

										}
									}
								}
							}
						}
					}
				}

			}

		}
	}

答案1

得分: 1

你不需要遍历地图中的所有键来判断它是否包含某个键。请参考以下示例:

if dict2, ok := dict1["foo"]; ok {
    if dict3, ok := dict2["bar"]; ok {
         if dict4, ok := dict3["goo"]; ok {
            // 然后继续
         } else {
            // 未找到键,出错
         }
    } else {
        // 未找到键,出错
    }
} else {
    // 未找到键,出错
}
英文:

You don't have to range over all the keys in a map to find out if it contains a key. See the following example:

if dict2, ok := dict1["foo"]; ok {
    if dict3, ok := dict2["bar"]; ok {
         if dict4, ok := dict3["goo"]; ok {
            // and so on
         } else {
            // key was not found, error
         }
    } else {
        // key was not found, error
    }
} else {
    // key was not found, error
}

答案2

得分: 1

使用结构体(structs)。有在线服务可以根据你的yaml文件自动生成结构体。有很多这样的服务,很容易找到。生成结构体后,你可以使用类似下面的代码:

package main

import (
	"fmt"
	"log"

	"github.com/go-yaml/yaml"
	"io/ioutil"
)

type User struct {
	Prof struct {
		Res []struct {
			Ed struct {
				App struct {
					Conf struct {
						Field1 int `yaml:"field1"`
						Field2 int `yaml:"field2"`
					} `yaml:"conf"`
				} `yaml:"app"`
			} `yaml:"ed"`
		} `yaml:"res"`
	} `yaml:"prof"`
}

func NewUser(name string) (*User, error) {
	user := new(User)

	file, err := ioutil.ReadFile(name)
	if err != nil {
		return nil, fmt.Errorf("read: %w", err)
	}

	if err := yaml.Unmarshal(file, user); err != nil {
		return nil, fmt.Errorf("unmarshal: %w", err)
	}

	return user, nil
}

func main() {
	user, err := NewUser("user.yaml")
	if err != nil {
		log.Fatalf("user: %s", err)
	}

	fmt.Printf("%+v\n", *user)
}
英文:

Use structs. There are online services to autogenerate the struct from your yaml file. There are many and they are easy to find. Generate a struct and then you can use something like this code:

package main

import (
	"fmt"
	"log"

	"github.com/go-yaml/yaml"
	"io/ioutil"
)

type User struct {
	Prof struct {
		Res []struct {
			Ed struct {
				App struct {
					Conf struct {
						Field1 int `yaml:"field1"`
						Field2 int `yaml:"field2"`
					} `yaml:"conf"`
				} `yaml:"app"`
			} `yaml:"ed"`
		} `yaml:"res"`
	} `yaml:"prof"`
}

func NewUser(name string) (*User, error) {
	user := new(User)

	file, err := ioutil.ReadFile(name)
	if err != nil {
		return nil, fmt.Errorf("read: %w", err)
	}

	if err := yaml.Unmarshal(file, user); err != nil {
		return nil, fmt.Errorf("unmarshal: %w", err)
	}

	return user, nil
}

func main() {
	user, err := NewUser("user.yaml")
	if err != nil {
		log.Fatalf("user: %s", err)
	}

	fmt.Printf("%+v\n", *user)
}

huangapple
  • 本文由 发表于 2022年4月26日 23:04:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/72016285.html
匿名

发表评论

匿名网友

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

确定