
每日一库之 viper:强大的配置解决方案
viper 是一个支持多种格式配置文件的解决库,今天我们来一起探索一下它的强大功能。
在开始使用 viper 之前,首先需要通过命令进行安装:
`$ go get /spf13/viper`
接下来我们来看一下快速使用的方式。首先创建一个配置文件 config.toml,并设置一些配置信息。然后,在 Go 程序中通过调用 viper 的相关函数来读取这些配置信息。
配置文件示例(config.toml):
toml
app_name = “awesome web”
log_level = “DEBUG” 可能的值包括:DEBUG、INFO、WARNING、ERROR、FATAL
[mysql]
ip = “127.0.0.1”
port = 3306
user = “dj”
password = “123456”
database = “awesome”
[redis]
ip = “127.0.0.1”
port = 7381
在 Go 程序中使用 viper 读取配置:
go
package main
import (
“fmt”
log”/spf13/viper”
)func main() {viper.SetConfigName(“config”)viper.SetConfigType(“toml”)viper.AddConfigPath(“.”)err := viper.ReadInConfig()if err != nil {log.Fatal(“read config failed:”, err)}fmt.Println(“app_name:”, viper.Get(“app_name”))fmt.Println(“log_level:”, viper.Get(“log_level”))fmt.Println(“mysql ip:”, viper.Get(“mysql.ip”))fmt.Println(“mysql port:”, viper.Get(“mysql.port”))fmt.Println(“mysql user:”, viper.Get(“mysql.user”))fmt.Println(“mysql password:”, viper.Get(“mysql.password”))fmt.Println(“mysql database:”, viper.Get(“mysql.database”))fmt.Println(“redis ip:”, viper.Get(“redis.ip”))fmt.Println(“redis port:”, viper.Get(“redis.port”))}
主程序包
导入所需模块:
“fmt”
“日志”
“时间”
以及第三方库 “/spf13/viper”
主函数开始:
我们使用viper来设置配置文件的相关参数。我们设定配置文件的名称为”config”,配置文件的格式为toml类型,并添加配置文件的路径为当前目录。然后,我们尝试读取配置文件,如果读取失败则记录致命错误并退出程序。
示例输出可能如下:
redis端口号在暂停前: 7381
redis端口号在暂停后: 73810
viper.OnConfigChange(func(e 事件) {
日志.Printf(“配置文件名称:%s 操作:%s”, e.Name, e.Op)
})
这样,每当配置文件发生变化时,都会执行这个回调函数,打印出相关的操作信息。这种实时反馈机制使我们的程序更加灵活和响应迅速。
