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
			}
		}
	}
posted @ 2023-03-14 18:26  单眼皮Boy  阅读(150)  评论(0)    收藏  举报