乔克视界 乔克视界
首页
  • 运维
  • 开发
  • 监控
  • 安全
  • 随笔
  • Docker
  • Golang
  • Python
  • AIOps
  • 心情杂货
  • 读书笔记
  • 面试
  • 实用技巧
  • 博客搭建
友链
关于
收藏
  • 分类
  • 标签
  • 归档

乔克

云原生爱好者
首页
  • 运维
  • 开发
  • 监控
  • 安全
  • 随笔
  • Docker
  • Golang
  • Python
  • AIOps
  • 心情杂货
  • 读书笔记
  • 面试
  • 实用技巧
  • 博客搭建
友链
关于
收藏
  • 分类
  • 标签
  • 归档
  • Docker

  • Golang

    • Golang基础知识

    • Golang进阶知识

    • Golang常用包

      • Cobra 使用
      • gorm的简单操作
      • Excelize操作excl
      • sjson为json数据设置值
      • gjson解析json数据
      • yaml配置文件解析
      • viper读取配置文件
        • 配置工具的选择
        • [](https://xuchao918.github.io/2019/04/29/%E4%BD%BF%E7%94%A8go%E8%AF%BB%E5%8F%96%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6/#%E5%AE%89%E8%A3%85viper)安装viper
          • [](https://xuchao918.github.io/2019/04/29/%E4%BD%BF%E7%94%A8go%E8%AF%BB%E5%8F%96%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6/#%E4%BD%BF%E7%94%A8viper%E8%AF%BB%E5%8F%96JSON%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6)使用viper读取JSON配置文件
          • [](https://xuchao918.github.io/2019/04/29/%E4%BD%BF%E7%94%A8go%E8%AF%BB%E5%8F%96%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6/#%E4%BD%BF%E7%94%A8viper%E8%AF%BB%E5%8F%96yaml%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6)使用viper读取yaml配置文件
          • [](https://xuchao918.github.io/2019/04/29/%E4%BD%BF%E7%94%A8go%E8%AF%BB%E5%8F%96%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6/#viper%E5%85%B6%E4%BB%96%E9%87%8D%E8%A6%81%E5%8A%9F%E8%83%BD)viper其他重要功能
        • [](https://xuchao918.github.io/2019/04/29/%E4%BD%BF%E7%94%A8go%E8%AF%BB%E5%8F%96%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6/#%E4%BD%BF%E7%94%A8goconfig%E8%AF%BB%E5%8F%96ini%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6)使用goconfig读取ini配置文件
      • zap日志管理
      • gopsutil获取系统信息
  • AIOps

  • 专栏
  • Golang
  • Golang常用包
乔克
2025-07-17
目录

viper读取配置文件

# 配置工具的选择

通常,在一个或多个项目中会有多种格式的配置文件,比如PHP的php.ini文件、Nginx的server.conf文件,那么使用Golang怎么去读取这些不同格式的配置文件呢?

比如常见的有 JSON文件、INI文件、YAML文件和TOML文件等等。其中这些文件,对应的Golang处理库如下:

  • encoding/json – 标准库中的包,可以处理JSON配置文件,缺点是不能加注释
  • gcfg&goconfig – 处理INI配置文件
  • toml – 处理TOML配置文件
  • viper – 处理JSON, TOML, YAML, HCL以及Java properties配置文件

通常情况下,推荐使用viper库来读取配置文件,虽然它不支持ini格式的配置文件,但我们可以使用goconfig 或gcfg.v1库读取ini 格式配置文件。

viper 支持以下功能:

  • 支持Yaml、Json、 TOML、HCL 等格式的配置文件
  • 可以从文件、 io.Reader 、环境变量、cli命令行读取配置
  • 支持自动转换的类型解析
  • 可以远程从Key/Value中读取配置,需要导入 viper/remote 包
  • 监听配置文件。以往我们修改配置文件后需要重启服务生效,而Viper使用watch函数可以让配置自动生效。

# (opens new window)安装viper

go get github.com/spf13/viper
go get github.com/fsnotify/fsnotify
1
2

# (opens new window)使用viper读取JSON配置文件

假设现在有一份 json 格式的配置文件 config.json

{
  "date": "2019-04-30",
  "mysql": {
    "url": "127.0.0.1:3306",
    "username": "root",
    "password": "123456"
  }
}
1
2
3
4
5
6
7
8

读取json配置文件

package main

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

func main() {
	viper.SetConfigName("config")     //设置配置文件的名字
	viper.AddConfigPath(".")           //添加配置文件所在的路径
	viper.SetConfigType("json")       //设置配置文件类型,可选
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Printf("config file error: %s\n", err)
		os.Exit(1)
	}
	urlValue := viper.Get("mysql.url")
	fmt.Println("mysql url:", urlValue)
        fmt.Printf("mysql url: %s\n mysql username: %s\n mysql password: %s", viper.Get("mysql.url"), viper.Get("mysql.username"), viper.Get("mysql.password"))
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

运行程序,查看效果

$ go run viper_json.go
mysql url: 127.0.0.1:3306
mysql url: 127.0.0.1:3306
mysql username: root
mysql password: 123456
1
2
3
4
5

# (opens new window)使用viper读取yaml配置文件

假设现在有一份yaml格式的配置文件 config_yaml.yaml

port: 10666
mysql:
  url: "127.0.0.1:3306"
  username: root
  password: 123456
1
2
3
4
5

读取yaml配置文件

package main

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

func main() {
	viper.SetConfigName("config_yaml")     //把json文件换成yaml文件,只需要配置文件名 (不带后缀)即可
	viper.AddConfigPath(".")           //添加配置文件所在的路径
	//viper.SetConfigType("json")       //设置配置文件类型
	err := viper.ReadInConfig()
	if err != nil {
		fmt.Printf("config file error: %s\n", err)
		os.Exit(1)
	}
	
	viper.WatchConfig()           //监听配置变化
        viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("配置发生变更:", e.Name)
})

	urlValue := viper.Get("mysql.url")
	fmt.Println("mysql url:", urlValue)
	fmt.Printf("mysql url: %s\nmysql username: %s\nmysql password: %s", viper.Get("mysql.url"), viper.Get("mysql.username"), viper.GetString("mysql.password"))   
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

# (opens new window)viper其他重要功能

获取子级配置

当配置层级关系较多的时候,有时候我们需要直接获取某个子级的所有配置,可以这样操作:

app:
  cache1:
    max-items: 100
    item-size: 64
  cache2:
    max-items: 200
    item-size: 80

1
2
3
4
5
6
7
8

如果要读取cache1下的max-items,只需要执行viper.Get(“app.cache1.max-items”)就可以了。

解析配置

可以将配置绑定到某个结构体、map上,有两个方法可以做到这一点:

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

var config Config
var mysql MySQL
err := Unmarshal(&config)            // 将配置解析到 config 变量
if err != nil {
    t.Fatalf("unable to decode into struct, %v", err)
}
err := UnmarshalKey("mysql", &mysql) // 将配置解析到 mysql 变量
if err != nil {
    t.Fatalf("unable to decode into struct, %v", err)
}
1
2
3
4
5
6
7
8
9
10
11
12
13

获取值

在Viper中,有一些根据值的类型获取值的方法,存在以下方法:

Get(key string) : interface{}
GetBool(key string) : bool
GetFloat64(key string) : float64
GetInt(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
1
2
3
4
5
6
7
8
9
10
11

如果 Get 函数未找到值,则返回对应类型的一个零值。可以通过 IsSet() 方法来检测一个健是否存在。

viper.GetString("logfile") 
if viper.GetBool("verbose") {
    fmt.Println("verbose enabled")
}
1
2
3
4

修改对应的配置

viper.Set("Verbose", true)
viper.Set("LogFile", LogFile)

1
2
3

# (opens new window)使用goconfig读取ini配置文件

安装goconfig

go get github.com/Unknwon/goconfig
1

假设database.conf配置文件,如下所示

[mysql]
username=root
password=123456
url=127.0.0.1:3306
[redis]
address=127.0.0.1:6379
1
2
3
4
5
6

使用goconfig读取ini格式配置文件

package main

import (
	"fmt"
	"github.com/Unknwon/goconfig"
	"os"
)

var cfg *goconfig.ConfigFile

func init() {
	config, err := goconfig.LoadConfigFile("database.conf")    //加载配置文件
	if err != nil {
		fmt.Println("get config file error")
		os.Exit(-1)
	}
	cfg = config
}

func GlobalConfig() {
	glob, _ := cfg.GetSection("mysql")      //读取全部mysql配置
	fmt.Println(glob)
}

func main() {
	password, _ := cfg.GetValue("mysql", "password")  //读取单个值
	fmt.Println(password)
	username, _ := cfg.GetValue("mysql", "username")  //读取单个值
	fmt.Println(username)
	err := cfg.Reload()   //重载配置
	if err != nil {
		fmt.Printf("reload config file error: %s", err)
	}
	GlobalConfig()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

加载完全局配置后,该配置长驻内存,需要动态加载的话,使用cfg.Reload()方法。

运行程序,效果如下。

$ go run goconfig.go
123456
root
map[password:123456 url:127.0.0.1:3306 username:root]
1
2
3
4
上次更新: 2025/07/18, 11:55:50
yaml配置文件解析
zap日志管理

← yaml配置文件解析 zap日志管理→

最近更新
01
2025年,SRE在企业中可以做哪些事
07-18
02
SRE 如何提升自己在团队中的影响力
07-18
03
使用Go开发MCP服务
07-18
更多文章>
Theme by Vdoing | Copyright © 2019-2025 乔克 | MIT License | 渝ICP备20002153号 |
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式