这是我的yaml文件:
db:
# table prefix
tablePrefix: tbl
# mysql driver configuration
mysql:
host: localhost
username: root
password: mysql
# couchbase driver configuration
couchbase:
host: couchbase://localhost我使用go-yaml库将yaml文件解压缩为变量:
config := make(map[interface{}]interface{})
yaml.Unmarshal(configFile, &config)配置值:
map[mysql:map[host:localhost username:root password:mysql] couchbase:map[host:couchbase://localhost] tablePrefix:tbl]如何在没有预定义结构类型的情况下访问配置中的db -> mysql ->用户名值
发布于 2016-08-30 16:03:16
YAML使用字符串键。你试过:
config := make(map[string]interface{})若要访问嵌套属性,请使用类型断言。
mysql := config["mysql"].(map[string][string])
mysql["host"]常见的模式是将泛型映射类型化成别名。
type M map[string]interface{}
config := make(M)
yaml.Unmarshal(configFile, &config)
mysql := config["mysql"].(M)
host := mysql["host"].(string)发布于 2016-08-30 16:31:50
如果不提前定义类型,则需要从遇到的每个断言中选择合适的类型:
if db, ok := config["db"].(map[interface{}]interface{}); ok {
if mysql, ok := db["mysql"].(map[interface{}]interface{}); ok {
username := mysql["username"].(string)
// ...
}
}https://stackoverflow.com/questions/39232012
复制相似问题