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 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步