Go语言学习: viper

Go语言里的配置管理
更新于: 2024-10-18 20:31:20

安装

go get github.com/spf13/viper

示例

name: steve
hobbies:
  - skateboarding
  - snowboarding
  - go
package main

import (
	"bytes"
	"fmt"
	"os"

	"github.com/spf13/viper"
)

func main() {
	viper.SetConfigType("yaml") // or viper.SetConfigType("YAML")
	yamlExample, _ := os.ReadFile("./config.yml")
	viper.ReadConfig(bytes.NewBuffer(yamlExample))
	// output testing values
	fmt.Println(viper.Get("name"), viper.Get("hobbies"))
	fmt.Println(viper.AllSettings())
}

viper是什么

Viper 是一个完整的 Go 应用程序配置解决方案,包括12因子应用程序。它设计为在应用程序中工作,可以处理所有类型的配置需求和格式。它支持:

我将用来做以下程序:(aric) 

  • cli 程序
  • webapp 程序
  • setting defaults
  • reading from JSON, TOML, YAML, HCL, envfile and Java properties config files
  • live watching and re-reading of config files (optional)
  • reading from environment variables
  • reading from remote config systems (etcd or Consul), and watching changes
  • reading from command line flags
  • reading from buffer
  • setting explicit values

功能列表

功能代码
给配置文件设置默认值
viper.SetDefault("ContentDir", "content")
viper.SetDefault("LayoutDir", "layouts")
viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})
读取配置文件
viper.SetConfigName("config") // name of config file (without extension)
viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath("/etc/appname/")   // path to look for the config file in
viper.AddConfigPath("$HOME/.appname")  // call multiple times to add many search paths
viper.AddConfigPath(".")               // optionally look for config in the working directory
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
	panic(fmt.Errorf("fatal error config file: %w", err))
}
写配置文件
viper.WriteConfig() // writes current config to predefined path set by 'viper.AddConfigPath()' and 'viper.SetConfigName'
viper.SafeWriteConfig()
viper.WriteConfigAs("/path/to/my/.config")
viper.SafeWriteConfigAs("/path/to/my/.config") // will error since it has already been written
viper.SafeWriteConfigAs("/path/to/my/.other_config")
观察变化
viper.OnConfigChange(func(e fsnotify.Event) {
	fmt.Println("Config file changed:", e.Name)
})
viper.WatchConfig()
读取文件
viper.SetConfigType("yaml") // or viper.SetConfigType("YAML")

// any approach to require this configuration into your program.
var yamlExample = []byte(`
Hacker: true
name: steve
hobbies:
- skateboarding
- snowboarding
- go
clothing:
  jacket: leather
  trousers: denim
age: 35
eyes : brown
beard: true
`)

viper.ReadConfig(bytes.NewBuffer(yamlExample))

viper.Get("name") // this would be "steve"
设置 override
viper.Set("Verbose", true)
viper.Set("LogFile", LogFile)
这个需要配置服务
viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001","/config/hugo.json")
viper.SetConfigType("json") 
// because there is no file extension in a stream of bytes,
// supported extensions are "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"
err := viper.ReadRemoteConfig()
点语法取值
{
    "host": {
        "address": "localhost",
        "ports": [5799, 9090]
    },
    "datastore": {
        "metric": {
            "host": "127.0.0.1",
            "port": 3099
        },
        "warehouse": {
            "host": "198.0.0.1",
            "port": 2112
        }
    }
}
GetString("datastore.metric.host") // (returns "127.0.0.1")
GetInt("host.ports.1") // returns 6029