我正在尝试为我的一个小项目解析一个 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
{[]}
我错过了什么?
最佳答案
好吧,这很愚蠢......
但它可以帮助其他人。
将值放在 ""中解决了这个问题。 例如。
name: "siteName1"
url: "http://siteUrl1"
关于在 Go 中解析 YAML : map in list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40783154/