go配置开源库viper

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

转载于:https://my.oschina.net/yang1992/blog/1825585

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值