<p>I don't know if this is allowed in this sub but I've spent an entire morning struggling to do something so simple, I'm at a loss.</p>
<p>I want to read in a config of different hosts. I've tried YAML and TOML and have had limited success. </p>
<p>Here is an example config I'd like to read in (in YAML):</p>
<pre><code>hostA:
ssh:
Port: 22
Interval: 2 minutes
hostB:
http:
Port: 80
Interval: 5 minutes
</code></pre>
<p>How would you accomplish this goal with YAML/TOML? </p>
<hr/>**评论:**<br/><br/>ripeassmango: <pre><p>if it's possible, maybe you want to change the format of your config
something like</p>
<pre><code>hosts
- name: A
method: ssh
port: 22
interval: 2
- name: B
method: http
port: 88
interval: 5
</code></pre>
<p>then you can use gopkg.in/yaml.v2 to parse it</p></pre>natefinch: <pre><p>This is what I was going to say. I think the number one problem people have with yaml is trying to make them too implicit, which makes them hard to parse. </p></pre>natefinch: <pre><p>Ain't pretty, but it works:</p>
<pre><code>package main
import (
"fmt"
yaml "gopkg.in/yaml.v2"
)
func main() {
h := map[string]map[string]ConnectionData{}
err := yaml.Unmarshal([]byte(content), &h)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("%#v\n", h)
}
func (c *ConnectionData) UnmarshalYAML(unmarshal func(interface{}) error) error {
m := map[string]interface{}{}
if err := unmarshal(&m); err != nil {
return err
}
if port, ok := m["Port"]; ok {
p, ok := port.(int)
if !ok {
return fmt.Errorf("invalid port: %v", p)
}
c.Port = p
}
if in, ok := m["Interval"]; ok {
i, ok := in.(string)
if !ok {
return fmt.Errorf("invalid interval: %v", in)
}
c.Interval = i
}
return nil
}
const content = `
hostA:
ssh:
Port: 22
Interval: 2 minutes
hostB:
http:
Port: 80
Interval: 5 minutes
`
</code></pre></pre>brokedown: <pre><p>I've used both, they're pretty straightforward. Check out <a href="https://github.com/spf13/pflag" rel="nofollow">https://github.com/spf13/pflag</a> for a package that can do both.</p>
<p>Edit: yes I linked the wrong package, I meant "github.com/spf13/viper"</p></pre>whippythellama: <pre><p>Just guessing, but I think you meant <a href="https://github.com/spf13/viper" rel="nofollow">https://github.com/spf13/viper</a> - same author, but it's his config parsing library rather than his command line flag handler. It handles YAML and TOML out of the box (as well as others).</p></pre>brokedown: <pre><p>Yep. I am using both and copied the wrong one. Thanks!</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传