gpt4 book ai didi

go - 我如何阅读这个 YAML?

转载 作者:行者123 更新时间:2023-12-01 22:41:18 28 4
gpt4 key购买 nike

我有一个如下所示的 YAML 配置文件

development: true
databases:
- label: masterdata
properties:
host: localhost
port: 54321
user: admin
password: nimda
dialect: postgres
dbname: business
- label: transactional
properties:
host: localhost
port: 54321
user: webuser
password: insecure
dialect: postgres
dbname: web
结构如下
type ApplicationConfiguration struct {
development bool `yaml:"development"`
databases []Properties `yaml:"databases"`
}

type Properties struct {
Label string `yaml:"label"`
Values map[string]string `yaml:"properties"`
}

使用库 gopkg.in/yaml.v2尝试阅读本文
config := ApplicationConfiguration{}
b, _ := ioutil.ReadFile(configPath)
marshalError := yaml.Unmarshal(b, &config)
但是 config中的数据库值总是 nil 并且 development 总是错误的,这意味着它根本没有被解码。如何阅读此配置,可能是我使用了错误的结构或 yaml 需要更改或不同的 API?

最佳答案

尝试使用以下结构解码它:

type ApplicationConfiguration struct {
Development bool `yaml:"development"`
Databases []struct {
Label string `yaml:"label"`
Properties struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
User string `yaml:"user"`
Password string `yaml:"password"`
Dialect string `yaml:"dialect"`
Dbname string `yaml:"dbname"`
} `yaml:"properties"`
} `yaml:"databases"`
如果您需要将 Prop 解码到 map 中,请尝试以下操作:
  • 使用 map [字符串]接口(interface){}
    类型属性结构{
    标签字符串 yaml:"label"值映射[字符串]接口(interface){} yaml:"properties"}

  • 将其编码为结构,然后使用以下示例:
    type databases interface{}

    var myMap map[string]interface{}
  • 使用 struct 并在之后处理它:
    if v.Kind() == reflect.Map {
    for _, key := range v.MapKeys() {
    strct := v.MapIndex(key)
    fmt.Println(key.Interface(), strct.Interface())
    }}
  • 关于go - 我如何阅读这个 YAML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63612057/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com