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)
}
相关推荐
Learn-Share_HY18 分钟前
[Linux]如何設置靜態IP位址?
linux·运维·tcp/ip·ubuntu·static ip
柑木25 分钟前
Meld-BeyondCompare开源替代品
后端·程序员·开源
超浪的晨25 分钟前
Java List 集合详解:从基础到实战,掌握 Java 列表操作全貌
java·开发语言·后端·学习·个人开发
盛夏绽放28 分钟前
Excel导出实战:从入门到精通 - 构建专业级数据报表的完整指南
开发语言·javascript·excel·有问必答
超浪的晨31 分钟前
Java Set 集合详解:从基础语法到实战应用,彻底掌握去重与唯一性集合
java·开发语言·后端·学习·个人开发
workflower1 小时前
活动图描述场景
开发语言·软件工程·需求分析·软件需求·敏捷流程
梦想的初衷~1 小时前
基于现代R语言【Tidyverse、Tidymodel】的机器学习方法
开发语言·机器学习·r语言
香蕉可乐荷包蛋1 小时前
Python学习之路(十三)-常用函数的使用,及优化
开发语言·python·学习
chian-ocean1 小时前
零基础入门:用C++从零实现TCP Socket网络小工具
网络·c++·tcp/ip
惜.己1 小时前
使用python的读取xml文件,简单的处理成元组数组
xml·开发语言·python·测试工具