dounong5373 2016-11-24 09:58
浏览 296

在Go中解析YAML:列表中的映射

I'm trying to parse a yaml file for a small project I have.

The goal is to have the app's infos in a config file including the address to the serverfile in case it need to be updated. It is in a config file for easy "editability" purposes.

The main thing is that there are some connectivity tests to be done before the app really starts. I'm trying to parse that file. It looks like this :

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

I wrote the following, I can get what's in app: but not what's in 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,"
Version : ", config.App.Version)

    fmt.Println(test)
}

As an output I get :

Application : MySuperApp
Version : 1
{[]}

What am I missing ?

  • 写回答

1条回答 默认 最新

  • duanhun3273 2016-11-24 10:13
    关注

    OK, it was quite stupid...

    But it can help others.

    Putting the values inside of " " solved the problem. eg.

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

报告相同问题?

悬赏问题

  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入