Go 读取配置文件--viper

2023-12-08后端3 分钟160 次阅读
AI 摘要salmon-ai

本文详细解析了 Go 配置管理工具 viper 的基本用法,包括安装方式、读取 YAML 和 TOML 配置文件、通过 Get 系列方法获取不同类型的配置值,以及使用 Set 覆盖已有配

前言

viper 是一个适用于 Go 应用程序的配置解决方案,拥有丰富的特性:

  • 设置默认值
  • 支持 JSON/TOML/YAML/HCL/envfile/Java properties 等多种格式的配置文件;
  • 实时监控和重新读取配置文件(可选);
  • 从环境变量、命令行选项和io.Reader中读取配置;
  • 从远程配置系统(如:etcd或Consul)读取并监控配置变化;
  • 从buffer读取配置
  • 代码逻辑中显示设置键值。

教程

1、安装

使用以下命令安装

sh 复制代码
go get -u github.com/spf13/viper

2、读取文件

目录结构

bash 复制代码
.
├── config
│   ├── test.toml
│   └── test.yml
├── go.mod
├── go.sum
├── toml
│   └── read_toml.go
└── yml
    └── read_yml.go

读取 yml 文件

配置文件

yml 复制代码
database:
  server: 8090
  ports:
    - 8001
    - 8001
    - 8002

servers:
  upload:
    ip: 10.0.0.1

读取文件示例

go 复制代码
package main

import (
	"fmt"
	"github.com/spf13/viper"
)

func main() {
	//设置文件路经
	viper.SetConfigFile("./config/test.yml")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
	//获取全部文件内容
	fmt.Println("all settings: ", viper.AllSettings())
	fmt.Println("--------------")
	//根据内容类型,解析出不同类型
	fmt.Println(viper.GetString("database.server"))
	fmt.Println(viper.GetIntSlice("database.ports"))
	fmt.Println("--------------")
	fmt.Println(viper.GetString("servers.upload.ip"))
}

运行结果
image.png

读取 toml 文件

配置文件

toml 复制代码
[database]
server = "192.168.1.1"
ports = [8001, 8001, 8002]

[servers]
[servers.upload]
ip = "10.0.0.1"

读取文件示例

go 复制代码
package main

import (
	"fmt"
	"github.com/spf13/viper"
)

func main() {
	//设置文件路经
	viper.SetConfigFile("./config/test.toml")
	err := viper.ReadInConfig()
	if err != nil {
		panic("err")
	}
	//获取全部文件内容
	fmt.Println("all settings: ", viper.AllSettings())
	fmt.Println("--------------")
	//根据内容类型,解析出不同类型
	fmt.Println(viper.GetString("database.server"))
	fmt.Println(viper.GetIntSlice("database.ports"))
	fmt.Println("--------------")
	fmt.Println(viper.GetString("servers.upload.ip"))
}

运行结果
image.png

3、覆盖配置

go 复制代码
import (
	"fmt"
	"github.com/spf13/viper"
)

func main() {
	//设置文件路经
	viper.SetConfigFile("./config/test.toml")
	err := viper.ReadInConfig()
	if err != nil {
		panic("err")
	}
	//获取全部文件内容
	fmt.Println("all settings: ", viper.AllSettings())
	fmt.Println("--------------")
	//根据内容类型,解析出不同类型
	fmt.Println(viper.GetString("database.server"))
	fmt.Println(viper.GetIntSlice("database.ports"))
	fmt.Println("--------------")
	fmt.Println(viper.GetString("servers.upload.ip"))
	fmt.Println("--------------")
	viper.Set("servers.upload.ip", "10.0.0.2")
	fmt.Println(viper.GetString("servers.upload.ip"))
}
image.png

4、远程Key/Value存储支持

在Viper中启用远程支持,需要在代码中匿名导入viper/remote这个包。

go 复制代码
import _ "github.com/spf13/viper/remote"

viper 将读取从 Key/Value 存储(例如:etcd或Consul)中的路径检索到的配置字符串(如JSON、TOML、YAML、HCL、envfile和Java properties格式)。

这些值的优先级高于默认值,但是会被从磁盘、flag或环境变量检索到的配置值覆盖。(译注:也就是说 viper 加载配置值的优先级为:磁盘上的配置文件>命令行标志位>环境变量>远程Key/Value存储>默认值。)

viper 使用 crypt 从 K/V 存储中检索配置,这意味着如果你有正确的 gpg 密匙,你可以将配置值加密存储并自动解密。加密是可选的。

你可以将远程配置与本地配置结合使用,也可以独立使用。
crypt 有一个命令行助手,你可以使用它将配置放入 K/V 存储中。crypt 默认使用在http://127.0.0.1:4001的etcd。

sh 复制代码
go get github.com/bketelsen/crypt/bin/crypt
crypt set -plaintext /config/hugo.json /Users/hugo/settings/config.json

确认值已经设置:

sh 复制代码
crypt get -plaintext /config/hugo.json

有关如何设置加密值或如何使用 Consul 的示例,请参见 crypt 文档。

5、监听文件变化

viper 可以自动监听文件修改,如果有修改,重新加载配置。因此不需要重启服务器,就能让配置生效,下边是开启示例。

go 复制代码
// 开启监听
vp.WatchConfig()
// 监听文件是否被修改
vp.OnConfigChange(func(e fsnotify.Event) {
	fmt.Println("Config file change!", e.Name)
})

6、反序列化

viper 支持将配置 Unmarshal 到一个结构体中,为结构体中的对应字段(首字母必须大写)赋值,这里我简单举例下。

配置结构

go 复制代码
package common

type CONFIG struct {
	Server Server
	Mysql  Mysql
	Log    Log
}

type Server struct {
	port string
}

type Mysql struct {
	Host     string
	Port     string
	Username string
	Password string
	Database string
}

type Log struct {
	LogPath   string
	LogLevel  string
	IsConsole bool
}

viper配置

go 复制代码
package common

import (
	"errors"
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

func InitViper() {
	vp := viper.New()
	vp.SetConfigFile("./file/config.yml")
	if err := vp.ReadInConfig(); err != nil {
		var configFileNotFoundError viper.ConfigFileNotFoundError
		if errors.As(err, &configFileNotFoundError) {
			// 配置文件未找到错误;如果需要可以忽略
			panic("Config not found in ")
		}
	} // 配置文件找到并成功解析
	vp.WatchConfig()
	// 监听文件是否被修改
	vp.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file change!", e.Name)
	})
	// Unmarshal 到一个结构体中,为结构体中的对应字段(首字母必须大写)赋值
	if err := vp.Unmarshal(&Config); err != nil {
		fmt.Println(err)
	}
}

main函数

go 复制代码
package main

import (
	"fmt"
	"gorm_study/common"
)

func main() {
	common.InitViper()
	fmt.Printf("username:%s\n", common.Config.Mysql.Username)
}

测试结果
image.png

觉得有用就点个赞,不用登录也能读

评论

0 条
登录 之后才能评论
—
还没有评论,来说第一句