golang viper 处理TOML 特殊的arrar和array of table

参考:https://github.com/spf13/viper/issues/213
知识点:go类型断言
toml config:

[src_isntances]
# i=[{ip="dasds",port="asdas"},{ip="dffdafs",port="afasdsdas"}]
i1=[{ip="localhost",port="1435",user="",password=""},{ ip="locdlhost",port="1435",user="",password=""}]
i2=[{ip="localhost",port="1437",user="",password=""},{ ip="l7st",port="1435",user="",password=""}]
[[lights]]
relay = 1
name = "Night"
[[lights]]
relay = 2
name = "Day"
[[lights]]
relay = 3
name = "Low Intensity"
[[lights]]
relay = 8
name = "Blackout"

go code:

type inst struct {
Ip string
Port string
User string
Password string
}
var i map[string][]inst
//instances
viper.UnmarshalKey("src_isntances", &i)
for _, v := range i {
fmt.Println(v)
}
presets, ok := viper.Get("lights").([]interface{})
if !ok {
fmt.Println("incorrectly configured light presents")
} else {
for _, table := range presets {
if m, ok := table.(map[string]interface{}); ok { // type assert here
fmt.Println(cast.ToInt(m["relay"])) // need cast, "github.com/spf13/cast"
// cast 'name' too
}
}
}

本文作者:KiGiBoy

本文链接:https://www.cnblogs.com/ls11736/p/17215912.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   单眼皮Boy  阅读(128)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起