配置管理工具 —— Go Viper 入门

本文通过丰富的代码示例演示了 Viper 的基本功能,读者可以跟随这些示例,学习如何使用 Viper

Viper

Viper 是一个用于 Go 语言应用程序的配置管理工具,它可以从不同的来源读取和解析配置信息。

安装

go get github.com/spf13/viper

注意:Viper 使用 Go Modules 来管理依赖项。

给 Viper 值

建立默认值

Viper 能够为我们的配置健设置默认值,如:

func main() {
	viper.SetDefault("ContentDir", "content")
	viper.SetDefault("LayoutDir", "layouts")
	viper.SetDefault("Taxonomies", map[string]string{
		"tag":      "tags",
		"category": "categories",
	})

	fmt.Println("ContentDir:", viper.GetString("ContentDir"))
	fmt.Println("LayoutDir:", viper.GetString("LayoutDir"))
	fmt.Println("Taxonomies:", viper.GetStringMapString("Taxonomies"))
}
go run main.go
#ContentDir: content
#LayoutDir: layouts
#Taxonomies: map[category:categories tag:tags]

读取配置文件

Viper 可以从多个路径搜索配置文件,但目前一个 Viper 实例只支持一个配置文件。

下面这个示例展示了如何使用 Viper 搜索和读取配置文件:

// filepath: ./main.go
func main() {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")

	viper.AddConfigPath("/etc/appname/")
	viper.AddConfigPath("$HOME/.appname")
	viper.AddConfigPath(".")

	if err := viper.ReadInConfig(); err != nil {
		panic(fmt.Errorf("fatal error config file: %w", err))
	}

	fmt.Println("appname:", viper.GetString("appname"))
	fmt.Println("version:", viper.GetString("version"))
	fmt.Println("debug:", viper.GetBool("debug"))
}
# filepath: ./config.yaml
appname: myapp
version: 1.0.0
debug: true
go run main.go
#appname: myapp
#version: 1.0.0
#debug: true

写入配置文件

读取配置文件很有用,但有时我们想存储运行时所作的所有修改。为此,viper 提供了一系列函数,每个函数都有自己的用途:

  • WriteConfig —— 将当前 viper 配置写入预定义的文件路径。如果预定义文件路径存在,则覆盖该文件;如果预定义文件路径不存在,则会产生一个 error

  • SafeWriteConfig —— 将当前 viper 配置写入预定义的文件路径。如果预定义文件路径存在,则会报错;如果预定义文件路径不存在,则会创建文件并写入,如:

    func main() {
    	viper.Set("appname", "myapp")
    	viper.Set("version", "1.0.0")
    	viper.Set("debug", "true")
    
    	viper.SetConfigName("config")
    	viper.SetConfigType("yaml")
    
    	viper.AddConfigPath("./")
    
    	if err := viper.SafeWriteConfig(); err != nil {
    		panic(fmt.Errorf("fatal error writing config file: %w", err))
    	}
    
    	fmt.Println("Config file written successfully")
    }
    
    go run main.go
    #panic: fatal error writing config file: Config File "D:\\workspace\\golang\\src\\viper-demo\\config.yaml" Already Exists
    
  • WriteConfigAs —— 将当前 viper 配置写入给定的文件路径。如果给定文件路径存在,则覆盖该文件;如果给定文件路径不存在,则会产生一个 error

  • SafeWriteConfigAs —— 将当前 viper 配置写入给定的文件路径。如果给定文件路径存在,则会报错;如果给定文件路径不存在,则会创建文件并写入,如:

    func main() {
    	viper.Set("appname", "myapp")
    	viper.Set("version", "1.0.0")
    	viper.Set("debug", "true")
    
    	if err := viper.SafeWriteConfigAs("./config.yaml"); err != nil {
    		panic(fmt.Errorf("fatal error writing config file: %w", err))
    	}
    
    	fmt.Println("Config file written successfully")
    }
    
    go run main.go
    #panic: fatal error writing config file: Config File "./config.yaml" Already Exists
    

监视配置文件

Viper 能够在应用程序运行时监视配置文件的更改,我们只需调用 viper 实例的 watchConfig 方法即可。我们也可以为 viper 提供一个回调函数,以便在每次发生更改时运行,如:

func main() {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")

	viper.AddConfigPath(".")

	if err := viper.ReadInConfig(); err != nil {
		panic(fmt.Errorf("fatal error reading config file: %w", err))
	}

	fmt.Println("appname:", viper.GetString("appname"))
	fmt.Println("version:", viper.GetString("version"))
	fmt.Println("debug:", viper.GetBool("debug"))

	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)

		fmt.Println("appname:", viper.GetString("appname"))
		fmt.Println("version:", viper.GetString("version"))
		fmt.Println("debug:", viper.GetBool("debug"))
	})

	viper.WatchConfig()

	fmt.Println("Press enter to exit...")
	_, _ = fmt.Scanln()
}
go run main.go
#appname: myapp
#version: 1.0.0
#debug: true
#Press enter to exit...
#Config file changed: D:\workspace\golang\src\viper-demo\config.yaml
#appname: mynewapp
#version: 2.0.0
#debug: false

从 io.Reader 读取配置

Viper 预定义了许多配置源,如文件、环境变量、标志和远程 K/V 存储,但并不受其约束。你也可以实现自己需要的配置源,并将其提供给 viper,如:

func main() {
	viper.SetConfigType("yaml")

	var yamlExample = []byte(`
Hacker: true
name: steve
hobbies: 
- skateboarding
- snowboarding
- go
clothing:
 jacket: leather
 trousers: denim
age: 35
eyes: brown
beard: true
`)

	if err := viper.ReadConfig(bytes.NewBuffer(yamlExample)); err != nil {
		panic(fmt.Errorf("fatal error reading config: %w", err))
	}

	fmt.Println("Hacker:", viper.GetBool("Hacker"))
	fmt.Println("name:", viper.GetString("name"))
	fmt.Println("hobbies:", viper.GetStringSlice("hobbies"))
	fmt.Println("clothing:", viper.GetStringMapString("clothing"))
	fmt.Println("age:", viper.GetInt("age"))
	fmt.Println("eyes:", viper.GetString("eyes"))
	fmt.Println("beard:", viper.GetBool("beard"))
}
go run main.go
#Hacker: true
#name: steve
#hobbies: [skateboarding snowboarding go]
#clothing: map[jacket:leather trousers:denim]
#age: 35
#eyes: brown
#beard: true

注册使用别名

别名允许多个键引用单个值,如:

func main() {
	viper.RegisterAlias("loud", "Verbose")

	viper.Set("Verbose", false)
	viper.Set("loud", true)

	fmt.Println("Verbose:", viper.GetBool("Verbose"))
	fmt.Println("loud:", viper.GetBool("loud"))
}
go run main.go
#Verbose: true
#loud: true

使用环境变量

Viper 完全支持环境变量,有五种方法可以帮助使用 ENV:

  • AutomaticEnv()
  • BindEnv(string...) : error
  • SetEnvPrefix(string)
  • SetEnvKeyReplacer(string...) *strings.Replacer
  • AllowEmptyEnv(bool)

在使用 ENV 变量时,必须认识到变量需要区分大小写。

Viper 提供了一种机制来确保 ENV 变量的唯一性。通过使用 SetEnvPrefix,你可以告诉 viper 在读取环境变量时使用一个前缀。BindEnvAutomaticEnv 都将使用该前缀。

BindEnv 需要一个或多个参数。第一个参数是键名,其余参数是要绑定到此键的环境变量的名称。如果提供了多个参数,它们将按指定顺序优先。环境变量的名称区分大小写。如果没有提供 ENV 变量名,Viper 将自动假定 ENV 变量符合以下格式:前缀 + “_” + 大写的键名。如果明确提供 ENV 变量名(第二个参数),则不会自动添加前缀。例如,如果第二个参数是 “id”,Viper 将查找 ENV 变量 “ID”。

使用 ENV 变量时要认识到的一件重要的事情是,那就是每次访问 ENV 变量时都要读取其值。调用 BindEnv 时,Viper 不会固定该值。

AutomaticEnv 是一个功能强大的辅助工具,尤其是与 SetEnvPrefix 结合使用时。当我们调用 AutomaticEnv,Viper 会在每次发出 viper.Get 请求时检查环境变量。它将应用以下规则:如果设置了环境变量,它会检查名称是否与键值一致,并以 EnvPrefix 作为前缀。

SetEnvKeyReplacer 允许使用 strings.Replacer 对象在一定程度上重写 Env 健。如果我们想在 Get() 调用中使用 - 或其他字符,但又想让环境变量使用 _ 分隔符,这将非常有用。在 viper_test 中可以找到使用它的实例。

另外,我们也可以使用带有 NewWithOptions 工厂函数的 EnvKeyReplacer。与 SetEnvKeyReplacer 不同,它接受 StringReplacer 接口,允许我们编写自定义的字符串替换逻辑。

默认情况下,空环境变量被视为未设置,并将回退到下一个配置源。要将空环境变量视为已设置,请使用 AllowEmptyEnv 方法。

Env 示例
func main() {
	viper.SetEnvPrefix("spf")

	_ = viper.BindEnv("id")

	_ = os.Setenv("SPF_ID", "13")

	fmt.Println("id:", viper.Get("id"))
}
go run main.go
#id: 13

使用标志

Viper 具有绑定标志的能力。具体来说,Viper 支持 Cobra 库中使用的 Pflags

BindEnv 类似,该值不是在调用绑定方法时设置的,而是在访问绑定方法时设置的。这意味着我们可以随时绑定,甚至可以在 init() 函数中绑定。

对于单个标志,BindPFlag() 方法提供了这一功能,如:

var serverCmd = &cobra.Command{
	Use:   "server",
	Short: "Run the server",

	Run: func(cmd *cobra.Command, args []string) {
		port := viper.GetInt("port")
		fmt.Println("Running server on port:", port)
	},
}

func init() {
	serverCmd.Flags().Int("port", 1138, "Port to run Application server on")
	_ = viper.BindPFlag("port", serverCmd.Flags().Lookup("port"))
}

func main() {
	_ = serverCmd.Execute()
}
go run main.go
#Running server on port: 1138

go run main.go --port=8080
#Running server on port: 8080

我们也可以绑定现有的 pflags 集(pflag.FlagSet),如:

func main() {
	pflag.Int("flagname", 1234, "help message for flagname")

	pflag.Parse()

	_ = viper.BindPFlags(pflag.CommandLine)

	i := viper.GetInt("flagname")

	fmt.Println("flagname:", i)
}
go run main.go
#flagname: 1234

go run main.go --flagname=4321
#flagname: 4321

在 Viper 中使用 pflag 并不妨碍使用 使用了 flag 的软件包。我们可以通过调用 pflag 包提供的 AddGoFlagSet() 函数,兼容 flag 包定义的标志 ,如:

func main() {
	flag.Int("flagname", 1234, "help message for flagname")

	pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
	pflag.Parse()

	_ = viper.BindPFlags(pflag.CommandLine)

	i := viper.GetInt("flagname")

	fmt.Println("flagname:", i)
}
go run main.go
#flagname: 1234

拿 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[string]string
  • GetStringSlice(key string) : []string
  • GetTime(key string) : time.Time
  • GetDuration(key string) : time.Duration
  • IsSet(key string) : bool
  • AllSettings() : map[string]interface{}

需要注意的一点是,如果没有找到键,每个 Get 函数都会返回一个零值。为了检查给定键是否存在,viper 提供了 IsSet() 方法。

以下是如何使用 Viper 读取 Go 中的配置文件的示例:

func main() {
	viper.SetConfigName("config")
	viper.AddConfigPath(".")

	if err := viper.ReadInConfig(); err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	fmt.Println("Reading values using Viper:")

	fmt.Println("logfile:", viper.GetString("logfile"))
	fmt.Println("verbose:", viper.GetBool("verbose"))
	fmt.Println("loglevel", viper.GetInt("loglevel"))
	fmt.Println("logdir:", viper.GetStringSlice("logdir"))
	fmt.Println("logdir[0]:", viper.GetStringSlice("logdir")[0])
	fmt.Println("logdir[1]:", viper.GetStringSlice("logdir")[1])
}
logfile: /var/log/myapp.log
verbose: true
loglevel: 2
logdir:
  - /var/log/myapp/
  - /var/log/myapp2/
go run main.go
#Reading values using Viper:
#logfile: /var/log/myapp.log
#verbose: true
#loglevel 2
#logdir: [/var/log/myapp/ /var/log/myapp2/]
#logdir[0]: /var/log/myapp/
#logdir[1]: /var/log/myapp2/

获取嵌套键

获取方法还接受格式化的路径,以访问深层嵌套键,如:

func main() {
	viper.AddConfigPath(".")
	viper.SetConfigName("config")
	viper.SetConfigType("json")

	if err := viper.ReadInConfig(); err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	fmt.Println("Reading values using Viper.")

	fmt.Println("datastore.metric.host:", viper.GetString("datastore.metric.host"))
	fmt.Println("datastore.metric.port:", viper.GetInt("datastore.metric.port"))
	fmt.Println("datastore.warehouse.host:", viper.GetString("datastore.warehouse.host"))
	fmt.Println("datastore.warehouse.port:", viper.GetString("datastore.warehouse.port"))
}
{
    "host": {
        "address": "localhost",
        "port": 5799
    },
    "datastore": {
        "metric": {
            "host": "127.0.0.1",
            "port": 3099
        },
        "warehouse": {
            "host": "198.0.0.1",
            "port": 2112
        }
    }
}
go run main.go
#Reading values using Viper.
#datastore.metric.host: 127.0.0.1
#datastore.metric.port: 3099
#datastore.warehouse.host: 198.0.0.1
#datastore.warehouse.port: 2112

Viper 可以使用路径中的数字访问数组索引,如:

func main() {
	viper.AddConfigPath(".")
	viper.SetConfigName("config")
	viper.SetConfigType("json")

	err := viper.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	fmt.Println("Reading values using Viper:")

	fmt.Println("host.address:", viper.GetString("host.address"))

	fmt.Println("host.ports[0]:", viper.GetInt("host.ports.0"))
	fmt.Println("host.ports[1]:", viper.GetInt("host.ports.1"))

	fmt.Println("datastore.metric.host:", viper.GetString("datastore.metric.host"))
	fmt.Println("datastore.metric.port:", viper.GetInt("datastore.metric.port"))
	
	fmt.Println("datastore.warehouse.host:", viper.GetString("datastore.warehouse.host"))
	fmt.Println("datastore.warehouse.port:", viper.GetInt("datastore.warehouse.port"))
}
{
  "host": {
    "address": "localhost",
    "ports": [
      5799,
      6029
    ]
  },
  "datastore": {
    "metric": {
      "host": "127.0.0.1",
      "port": 3099
    },
    "warehouse": {
      "host": "198.0.0.1",
      "port": 2112
    }
  }
}
go run main.go
#Reading values using Viper:
#host.address: localhost
#host.ports[0]: 5799
#host.ports[1]: 6029
#datastore.metric.host: 127.0.0.1
#datastore.metric.port: 3099
#datastore.warehouse.host: 198.0.0.1
#datastore.warehouse.port: 2112

如果存在与分隔键路径匹配的键,则会返回其值,如:

func main() {
	viper.AddConfigPath(".")
	viper.SetConfigName("config")
	viper.SetConfigType("json")

	if err := viper.ReadInConfig(); err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	fmt.Println("Reading values using Viper:")
	fmt.Println("datastore.metric.host:", viper.GetString("datastore.metric.host"))
}
{
  "datastore.metric.host": "0.0.0.0",
  "host": {
    "address": "localhost",
    "port": 5799
  },
  "datastore": {
    "metric": {
      "host": "127.0.0.1",
      "port": 3099
    },
    "warehouse": {
      "host": "198.0.0.1",
      "port": 2112
    }
  }
}
go run main.go
#Reading values using Viper:
#datastore.metric.host: 0.0.0.0

提取子树

在开发可重用模块时,提取配置的子集并将其传递给模块通常很有用。这样,模块就能以不同的配置被实例化多次,如:

type Cache struct {
	MaxItems int
	ItemSize int
}

func NewCache(v *viper.Viper) *Cache {
	return &Cache{
		MaxItems: v.GetInt("max-items"),
		ItemSize: v.GetInt("item-size"),
	}
}

func main() {
	viper.AddConfigPath(".")
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")

	if err := viper.ReadInConfig(); err != nil {
		panic(err)
	}

	cache1Config := viper.Sub("cache.cache1")
	if cache1Config == nil {
		panic("cache configuration not found")
	}
	cache1 := NewCache(cache1Config)

	fmt.Println("cache1 max items:", cache1.MaxItems)
	fmt.Println("cache1 item size:", cache1.ItemSize)

	cache2Config := viper.Sub("cache.cache2")
	if cache2Config == nil {
		panic("cache configuration not found")
	}
	cache2 := NewCache(cache2Config)

	fmt.Println("cache2 max items:", cache2.MaxItems)
	fmt.Println("cache2 item size:", cache2.ItemSize)
}
cache:
  cache1:
    max-items: 100
    item-size: 64
  cache2:
    max-items: 200
    item-size: 80
go run main.go
#cache1 max items: 100
#cache1 item size: 64
#cache2 max items: 200
#cache2 item size: 80

反序列化

我们还可以将所有或特定值反序列化成结构体、map 等。

有两种方法可以做到这一点:

  • Unmarshal(rawVal interface{}) : error
  • UnmarshalKey(key string, rawVal interface{}) : error

以下示例演示了如何使用 Unmarshal 方法将 YAML 配置反序列化为自定义结构:

type config struct {
	Port    int
	Name    string
	PathMap string `mapstructure:"path_map"`
}

var C config

func main() {
	viper.AddConfigPath(".")
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")

	if err := viper.ReadInConfig(); err != nil {
		panic(err)
	}

	if err := viper.Unmarshal(&C); err != nil {
		panic(err)
	}

	fmt.Println("Port:", C.Port)
	fmt.Println("Name:", C.Name)
	fmt.Println("PathMap:", C.PathMap)
}
port: 8080
name: "MyApp"
path_map: "/home/user/myapp"
go run main.go
#Port: 8080
#Name: MyApp
#PathMap: /home/user/myapp

如果要反序列化的键值本身包含点(默认键值分隔符)的配置,则必须更改分隔符,如:

type config struct {
	Chart struct {
		Values map[string]interface{}
	}
}

var C config

func main() {
	v := viper.NewWithOptions(viper.KeyDelimiter("::"))

	v.AddConfigPath(".")
	v.SetConfigName("config")
	v.SetConfigType("yaml")

	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}

	if err := v.Unmarshal(&C); err != nil {
		panic(err)
	}

	fmt.Println("Chart values:", C.Chart.Values)
}
chart::values:
  ingress:
    annotations:
      traefik.frontend.rule.type: "PathPrefix"
      traefik.ingress.kubernetes.io/ssl-redirect: "true"
go run main.go
#Chart values: map[ingress:map[annotations:map[traefik.frontend.rule.type:PathPrefix traefik.ingress.kubernetes.io/ssl-redirect:true]]]

Viper 还支持将配置反序列化为嵌入式结构,如:

type config struct {
	Module struct {
		Enabled bool

		moduleConfig `mapstructure:",squash"` // 将嵌入解构的字段展平到父结构中
	}
}

type moduleConfig struct {
	Token string
}

var C config

func main() {
	viper.AddConfigPath(".")
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")

	if err := viper.ReadInConfig(); err != nil {
		panic(err)
	}

	if err := viper.Unmarshal(&C); err != nil {
		panic(err)
	}

	fmt.Println("Module enabled:", C.Module.Enabled)
	fmt.Println("Module token:", C.Module.Token)
}
module:
  enabled: true
  token: 89h3f98hbwf987h3f98wenf89ehf
go run main.go
#Module enabled: true
#Module token: 89h3f98hbwf987h3f98wenf89ehf

序列化到字符串

我们可能需要将 viper 中的所有设置序列化成字符串,而不是写入文件。我们可以将我们喜欢的格式的编组器与 AllSettings() 返回的配置一起使用,如:

func yamlStringSettings() string {
	c := viper.AllSettings()
	bs, err := yaml.Marshal(c)
	if err != nil {
		log.Fatalf("unable to marshal config to YAML: %v", err)
	}
	return string(bs)
}

func main() {
	viper.Set("name", "Alice")
	viper.Set("age", 25)
	viper.Set("hobbies", []string{"reading", "writing", "coding"})

	yamlString := yamlStringSettings()

	fmt.Println(yamlString)
}
go run main.go
#age: 25
#hobbies:
#- reading
#- writing
#- coding
#name: Alice

本文由 Sue211213 原创,发表于 2023 年 8 月 14 日,转载请注明出处和作者,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值