【问题标题】:Parsing YAML in Go : map in list在 Go 中解析 YAML:列表中的映射
【发布时间】:2017-04-08 13:34:53
【问题描述】:

我正在尝试为我的一个小项目解析一个 yaml 文件。

目标是在配置文件中包含应用程序的信息,包括服务器文件的地址,以防需要更新。它位于配置文件中,便于“编辑”。

主要是在应用程序真正启动之前需要完成一些连接测试。我正在尝试解析该文件。 它看起来像这样:

conf.yaml

app:
    version:    "1"
    name:       MySuperApp
    configLocation:   http://configaddress

test_url:
  -
    name:       siteName1
    url:        http://siteUrl1
  -
    name:       siteName2
    url:        http://siteUrl2
    proxy_port: 5678

我写了以下内容,我可以得到 app 中的内容:但不能得到 test_url 中的内容:

package main

import (
    "fmt"
    "io/ioutil"
    "path/filepath"
    "gopkg.in/yaml.v2"
)

type AppInfo struct {
    Name    string  `yaml:"name"`
    Version string  `yaml:"version"`
}

type Config struct {
    App AppInfo `yaml:"app"`
}

type TestUrl struct {
    Name        string `yaml:"name"`
    Url         string `yaml:"url"`
    ProxyPort   string `yaml:"proxy_port,omitempty"`
}

type TestUrls struct {
    ATest []TestUrl `yaml:"test_url"`
}

func main() {
    filename, _     := filepath.Abs("./config/conf.yaml")
    yamlFile, err   := ioutil.ReadFile(filename)

    if err != nil {
        panic(err)
    }

    var config Config
    err = yaml.Unmarshal(yamlFile, &config)
    if err != nil {
        panic(err)
    }

    var test TestUrls
    err = yaml.Unmarshal(yamlFile, &test)
    if err != nil {
        panic(err)
    }

    fmt.Println("Application : ", config.App.Name,"\nVersion : ", config.App.Version)

    fmt.Println(test)
}

作为输出我得到:

Application : MySuperApp
Version : 1
{[]}

我错过了什么?

【问题讨论】:

  • 给定的文件和代码在这里运行得很好。 Application : MySuperApp Version : 1 {[{siteName1 http://siteUrl1 } {siteName2 http://siteUrl2 5678}]}

标签: parsing go yaml


【解决方案1】:

好吧,这很愚蠢......

但它可以帮助别人。

将值放在 " " 中解决了这个问题。 例如。

name:       "siteName1"
url:        "http://siteUrl1"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多