go语言的配置管理需要一个比较友好的配置管理库,推荐一个网上第三方的开源库viper
使用实例:
func main() {
gameConfig := viper.New()
gameConfig.SetConfigName("game") // name of config file (without extension)
gameConfig.AddConfigPath("./config") // optionally look for config in the working directory
gameConfig.SetConfigType("json")
err := gameConfig.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
fmt.Println(gameConfig.GetString("server_name"))
fmt.Println(gameConfig.GetInt("player_limit_max"))
fmt.Println(gameConfig.GetBool("print_to_console"))
fmt.Println(gameConfig.Sub("match_server").GetInt("index"))
}
示例配置文件:
{
"server_name": "match",
"player_limit_max": 15,
"print_to_console": true,
"match_server": {
"index": 1,
"host": "127.0.0.1",
"rpc_port": 20012
}
}
程序执行结果:
match
15
true
1
总之,viper配置管理方式还是挺友好的,可以支持各种格式配置文件解析,并且配置文件内容读写操作就好友多了
第三方库的地址:https://github.com/spf13/viper