How would you handle this in golang?

agolangf · · 289 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I don&#39;t know if this is allowed in this sub but I&#39;ve spent an entire morning struggling to do something so simple, I&#39;m at a loss.</p> <p>I want to read in a config of different hosts. I&#39;ve tried YAML and TOML and have had limited success. </p> <p>Here is an example config I&#39;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&#39;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&#39;t pretty, but it works:</p> <pre><code>package main import ( &#34;fmt&#34; yaml &#34;gopkg.in/yaml.v2&#34; ) func main() { h := map[string]map[string]ConnectionData{} err := yaml.Unmarshal([]byte(content), &amp;h) if err != nil { fmt.Println(err) return } fmt.Printf(&#34;%#v\n&#34;, h) } func (c *ConnectionData) UnmarshalYAML(unmarshal func(interface{}) error) error { m := map[string]interface{}{} if err := unmarshal(&amp;m); err != nil { return err } if port, ok := m[&#34;Port&#34;]; ok { p, ok := port.(int) if !ok { return fmt.Errorf(&#34;invalid port: %v&#34;, p) } c.Port = p } if in, ok := m[&#34;Interval&#34;]; ok { i, ok := in.(string) if !ok { return fmt.Errorf(&#34;invalid interval: %v&#34;, 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&#39;ve used both, they&#39;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 &#34;github.com/spf13/viper&#34;</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&#39;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

289 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传