开发者

go配置管理框架viper常用操作

目录
  • 配置
  • 从Viper获取值
  • 通过传入.分隔的路径
  • 提取子树
  • 反序列化

官网地址:http://www.devze.com

github - spf13/viper: Go configuration with fangs

常用操作:

Viper会按照下面的优先级。每个项目的优先级都高于它下面的项目:

  • 显示调用Set设置值
  • 命令行参数(flag)
  • 环境变量
  • 配置文件
  • key/value存储
  • 默认值
编程

配置文件 config.yaml(当前目录下)

host: "0.0.0.0"
mysql:
  host: "127.0.0.1"
  port: 3306
cache:
  cache1:
    max-items: 100
    item-size: 64
  cache2:
    max-items: 200
    item-size: 80

配置

viper.SetDefault("Redis.port", "localhost:6379")
	// viper.SetConfigFile("./config.yaml") // 配置文件路径,此行和下面两行效果相同
	viper.SetConfigName("config") // 配置文件名
	viper.SetConfigType("yaml")   // 配置文件类型
	viper.AddConfigPath("./")     // 配置文件路径
	err := viper.ReadInConfig()   // 查找并读取配置文件
	if err != nil {
		panic(fmt.Errorf("fatal error config file: %w", err)) // 处理错误
	}

从Viper获取值

在Viper中,有几种方法可以根据值的类型获取值。存在以下功能和方法:

  • Get(key string) : interface{}
  • GetBool(key string) : bool
  • GetFloat64(key string) : float64
  • GetInt(key string) : int
  • GetIntSlice(key string) : []int
  • GetString(key string) : string
  • GetStringMap(key string) : map[string]interface{}
  • GetStringMapString(key string) : map[strinhttp://www.devze.comg]string
  • GetStringSlice(key string) : []string
  • GetTime(key string) : time.Time
  • GetDuration(key string) : time.Duration
  • IsSet(key string) : bool
  • AllSettings() : map[string]interface{}

通过传入.分隔的路径

// Viper可以通过传入.分隔的路径来访问嵌套字段:
	mysqlHost := viper.GetString("mysql.host") // 访问mysql的host字段
	fmt.Println("Mysql Host:", mysqlHost)
	mysqlPort := viper.GetInt("mysql.port") // 访问mysql的port字段
	fmt.Println("Mysql Port:", mysqlPort)

提取子树

// 提取子树
	appConfig := viper.Sub("app")                       // 提取app子树
	fmt.Println("App Config:", appConfig.AllSettings()) // 打印app子树的所有设置
	cache1 := appConfig.GetStringMapString("cache1")    // 提取app子树的cache1字段
	cache2 := viper.Sub("app.cache2")                   // 提取app子树的cache2字编程段
	fmt.Println("Cache1:", cache1)                      // 打印app子树的cache字段
	fmt.Println("Cache2:", cache2.AllSettings())        // 打印app子树的cache2字段的所有设置

反序列化

// 反序列化
	var conf Config
	err = pythonviper.Unmarshal(&conf) // 反序列化到结构体
	if err != nil {
		panic(fmt.Errorf("unable to decode into struct, %v", err)) // 处理错误
	}
	fmt.Println("Config Struct:", conf) // 打印反序列化后的结构体

到此这篇关于go配置管理框架viper的文章就介绍到这了,更多相关go配置管理viper内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜