golang viper配置文件管理

Viper是适用于Go应用程序的完整配置解决方案。它被设计用于在应用程序中工作,并且可以处理所有类型的配置需求和格式。它支持以下特性:

(1)设置默认值

(2)从JSON、TOML、YAML(YAML教程)、HCL、envfile和Java properties格式的配置文件读取配置信息

(3) 实时监控和重新读取配置文件(可选)

(4)从环境变量中读取

(5)从远程配置系统(etcd或Consul)读取并监控配置变化

(6)从命令行参数读取配置

(7)从buffer读取配置

(8)显式配置值

Viper安装

cpp 复制代码
go get github.com/spf13/viper
简单使用

目录结构

config.yaml

cpp 复制代码
name: ' user'

main.go

cpp 复制代码
package main

import (
	"fmt"

	"github.com/spf13/viper"
)

func main() {
	v := viper.New()
	v.SetConfigFile("config.yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	fmt.Println(v.Get("name"))
}

cd到viper_test目录运行(go build main.go)

将配置文件映射成struct

cpp 复制代码
package main

import (
	"fmt"

	"github.com/spf13/viper"
)

type ServerConfig struct {
	ServerName string `mapstructure:"name"`
}

func main() {
	v := viper.New()
	v.SetConfigFile("config.yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	serverConfig := ServerConfig{}
	if err := v.Unmarshal(&serverConfig); err != nil {
		panic(err)
	}
	fmt.Println(serverConfig)
	fmt.Println(v.Get("name"))
}
嵌套映射

config.yaml

cpp 复制代码
name: ' user'
mysql:
  host: '127.0.0.1'
  port: 3306

main.go

cpp 复制代码
package main

import (
	"fmt"

	"github.com/spf13/viper"
)

type MysqlConfig struct {
	Host string `mapstruct:"host"`
	Port int    `mapstruct:"port"`
}
type ServerConfig struct {
	ServerName string      `mapstructure:"name"`
	MysqlInfo  MysqlConfig `mapstructure:"mysql"`
}

func main() {
	v := viper.New()
	v.SetConfigFile("config.yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	serverConfig := ServerConfig{}
	if err := v.Unmarshal(&serverConfig); err != nil {
		panic(err)
	}
	fmt.Println(serverConfig)
	fmt.Println(v.Get("name"))
}
开发环境和生产环境隔离配置

设置环境变量

cpp 复制代码
vim  ~/.zshrc
cpp 复制代码
export VIPER_DEBUG=true
cpp 复制代码
source ~/.zshrc

config-pro.yaml是生产环境的路径,config-debug.yaml是开发环境的路径

cpp 复制代码
package main

import (
	"fmt"

	"github.com/spf13/viper"
)

type ServerConfig struct {
	ServerName string `mapstructure:"name"`
}

func GetEnvInfo(env string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(env)
}
func main() {
	debug := GetEnvInfo("VIPER_DEBUG")
	configFileName := "config-pro.yaml"
	if debug {
		configFileName = "config-debug.yaml"
	}
	v := viper.New()
	v.SetConfigFile(configFileName)
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	serverConfig := ServerConfig{}
	if err := v.Unmarshal(&serverConfig); err != nil {
		panic(err)
	}
	fmt.Println(serverConfig)
	fmt.Println(v.Get("name"))
}
动态监听配置文件变化

运行完之后需要更改yaml文件并保存

cpp 复制代码
package main

import (
	"fmt"
	"time"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

type MysqlConfig struct {
	Host string `mapstruct:"host"`
	Port int    `mapstruct:"port"`
}
type ServerConfig struct {
	ServerName string      `mapstructure:"name"`
	MysqlInfo  MysqlConfig `mapstructure:"mysql"`
}

func GetEnvInfo(env string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(env)
}
func main() {
	v := viper.New()
	v.SetConfigFile("config.yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}
	serverConfig := ServerConfig{}
	if err := v.Unmarshal(&serverConfig); err != nil {
		panic(err)
	}
	fmt.Println(serverConfig)
	fmt.Println(v.Get("name"))
	//动态监听变化
	v.WatchConfig()
	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed:", e.Name)
		_ = v.ReadInConfig()
		_ = v.Unmarshal(&serverConfig)
		fmt.Println(serverConfig)
	})
	time.Sleep(time.Second * 60)
}
相关推荐
为思念酝酿的痛2 小时前
POSIX信号量
linux·运维·服务器·后端
小羊在睡觉2 小时前
力扣84. 柱状图中最大的矩形
后端·算法·leetcode·golang·go
AI玫瑰助手3 小时前
Python函数:默认参数的定义与注意事项
开发语言·python·信息可视化
油炸自行车3 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
肩上风骋3 小时前
C++14特性
开发语言·c++·c++14特性
swipe3 小时前
Neo4j + Graph RAG 医疗知识图谱工程实践:患者教育问答真正需要的是“关系可追溯”
后端·langchain·llm
IT大白鼠3 小时前
RSTP协议原理与配置详解:快速生成树技术的深度解析
网络·网络协议
源码宝4 小时前
MES系统源码:Java8 + SpringBoot2.7 + MySQL8 + Redis,后端源码清爽易扩展
java·后端·源码·springboot·mes系统·源码二开·mes源码
JAVA社区5 小时前
Java高级全套教程(十)—— SpringCloudAlibaba超详细实战详解
java·开发语言·spring cloud·面试·职场和发展
弥树子5 小时前
踩坑记录:服务器内网调用接口,真实请求URL与官方公开URL不一致问题排查
开发语言·php