golang配置读取值viper
viper简介
Viper是Go应用程序的完整配置解决方案,包括12-Factor应用程序。它旨在在应用程序中工作,并且可以处理所有类型的配置需求和格式。它支持:
- 设置默认值
- 从
JSON、TOML、YAML、HCL、envfile和Java属性配置文件中读取 - 实时观看和重新读取配置文件(可选)
- 从环境变量中读取
- 从远程配置系统(etcd 或 Consul)读取,并观察变化
- 从命令行标志读取
- 从缓冲区读取
- 设置显式值
读取配置文件
app.yaml
server:
host: 0.0.0.0
port: 9090
log:
level: debug
format: json
main.go
创建配置文件结构体
var cfg Cfg
type Cfg struct {
Server Server `yaml:"server"`
Log Log `yaml:"log"`
}
type Server struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
}
type Log struct {
Level string `yaml:"level"`
Format string `yaml:"format"`
}
使用viper读取配置文件并解析到结构体
1func initConfig() {
2 viper.AddConfigPath("./")
3 viper.SetConfigName("apps")
4 viper.SetConfigType("yaml")
5 if err := viper.ReadInConfig(); err != nil {
6 log.Fatalf("read config file failed, %v", err)
7 }
8 if err := viper.Unmarshal(&cfg); err != nil {
9 log.Printf("unmarshal config file failed, %v", err)
10 }
11 log.Printf("%#v", cfg)
12}
Copy
设置日志相关参数
1func initLog() {
2 switch strings.ToLower(cfg.Log.Level) {
3 case "panic":
4 logrus.SetLevel(logrus.PanicLevel)
5 case "fatal":
6 logrus.SetLevel(logrus.FatalLevel)
7 case "error":
8 logrus.SetLevel(logrus.ErrorLevel)
9 case "warn", "warning":
10 logrus.SetLevel(logrus.WarnLevel)
11 case "info":
12 logrus.SetLevel(logrus.InfoLevel)
13 case "debug":
14 logrus.SetLevel(logrus.DebugLevel)
15 case "trace":
16 logrus.SetLevel(logrus.TraceLevel)
17 default:
18 logrus.SetLevel(logrus.InfoLevel)
19 }
20 switch strings.ToLower(cfg.Log.Format) {
21 case "json":
22 logrus.SetFormatter(&logrus.JSONFormatter{})
23 case "text":
24 logrus.SetFormatter(&logrus.TextFormatter{})
25 default:
26 logrus.SetFormatter(&logrus.TextFormatter{})
27 }
28}
Copy
main函数
1func main() {
2 r := gin.Default()
3 logrus.Debug("i'm a debug log")
4 logrus.Info("i'm a info log")
5 logrus.Warn("i'm a warn log")
6 logrus.Error("i'm a error log")
7 r.Run(cfg.Server.Host + ":" + strconv.Itoa(cfg.Server.Port))
8}
Copy
运行
1go run main.go
Copy
输出结果
12021/06/30 10:12:16 main.Cfg{Server:main.Server{Host:"0.0.0.0", Port:9090}, Log:main.Log{Level:"debug", Format:"json"}}
2[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
3
4[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
5 - using env: export GIN_MODE=release
6 - using code: gin.SetMode(gin.ReleaseMode)
7
8{"level":"debug","msg":"i'm a debug log","time":"2021-06-30T10:12:16+08:00"}
9{"level":"info","msg":"i'm a info log","time":"2021-06-30T10:12:16+08:00"}
10{"level":"warning","msg":"i'm a warn log","time":"2021-06-30T10:12:16+08:00"}
11{"level":"error","msg":"i'm a error log","time":"2021-06-30T10:12:16+08:00"}
12[GIN-debug] Listening and serving HTTP on 0.0.0.0:9090
Copy
可以看到已经从配置文件读取到配置了。
从环境变量读取配置
1.修改initConfig函数,开启自动注入环境变量功能
在读取配置文件之前使用AutomaticEnv,并使用SetEnvKeyReplacer将".“替换为”" 注:如果是yaml字段有使用到"",可以替换成其他的,或者使用"__"
环境变量的格式为:SERVER_PORT
1...
2 viper.SetConfigType("yaml")
3 viper.AutomaticEnv()
4 replacer := strings.NewReplacer(".", "_")
5 viper.SetEnvKeyReplacer(replacer)
6 if err := viper.ReadInConfig(); err != nil {
7...
Copy
2.运行测试
1SERVER_PORT=10086 go run main.go
Copy
12021/06/30 15:45:19 main.Cfg{Server:main.Server{Host:"", Port:10086}, Log:main.Log{Level:"debug", Format:"json"}}
2[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
3
4[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
5 - using env: export GIN_MODE=release
6 - using code: gin.SetMode(gin.ReleaseMode)
7
8{"level":"debug","msg":"i'm a debug log","time":"2021-06-30T15:45:19+08:00"}
9{"level":"info","msg":"i'm a info log","time":"2021-06-30T15:45:19+08:00"}
10{"level":"warning","msg":"i'm a warn log","time":"2021-06-30T15:45:19+08:00"}
11{"level":"error","msg":"i'm a error log","time":"2021-06-30T15:45:19+08:00"}
12[GIN-debug] Listening and serving HTTP on :10086
Copy
看到端口已经自动变成10086了。
修改日志相关变量
1LOG_LEVEL=info LOG_FORMAT=text go run viper.go
Copy
可以看到日志级别和日志格式已经为环境变量指定的了。
12021/06/30 15:46:50 main.Cfg{Server:main.Server{Host:"", Port:9090}, Log:main.Log{Level:"info", Format:"text"}}
2[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.
3
4[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
5 - using env: export GIN_MODE=release
6 - using code: gin.SetMode(gin.ReleaseMode)
7
8INFO[0000] i'm a info log
9WARN[0000] i'm a warn log
10ERRO[0000] i'm a error log
11[GIN-debug] Listening and serving HTTP on :9090
golang配置读取值viper的更多相关文章
- Golang项目的配置管理——Viper简易入门配置
Golang项目的配置管理--Viper简易入门配置 What is Viper? From:https://github.com/spf13/viper Viper is a complete co ...
- Viper--方便好用的Golang 配置库
前言 本文主要是为读者介绍一个轻便好用的Golang配置库viper 正文 viper 的功能 viper 支持以下功能: 1. 支持Yaml.Json. TOML.HCL 等格式的配置 ...
- MFC 全局配置 读取保存配置
不知道关于全局配置别人都是怎么处理的,最近做的东西都用到全局配置,而且要保存软件的设置,下次启动时要使用上次关闭时的配置. 我的做法是建一个类用来保存和读取配置,并且在这个类中创建一些变量,供所有的界 ...
- springcloud config配置读取优先级
情景描述 最近在修复Eureka的静态页面加载不出的缺陷时,最终发现是远程GIT仓库将静态资源访问方式配置给禁用了(spring.resources.add-mappings=false).虽然最后直 ...
- 外部配置属性值是如何被绑定到XxxProperties类属性上的?--SpringBoot源码(五)
注:该源码分析对应SpringBoot版本为2.1.0.RELEASE 1 前言 本篇接 SpringBoot是如何实现自动配置的?--SpringBoot源码(四) 温故而知新,我们来简单回顾一下上 ...
- .NET Core技术研究-配置读取
升级ASP.NET Core后,配置的读取是第一个要明确的技术.原先的App.Config.Web.Config.自定义Config在ASP.NET Core中如何正常使用.有必要好好总结整理一下,相 ...
- spring boot下为配置属性值加密的正确姿势
最近做电商系统,安全性要求比较高,针对配置属性值的加密自然也是需要增强的点之一,那么如何加密呢? 网上搜索了些,有jasypt加密mysql密码的最为普遍,可惜问题就在于只能加密mysql信息,其他的 ...
- SpringBoot基础学习(二) SpringBoot全局配置文件及配置文件属性值注入
全局配置文件 全局配置文件能够对一些默认配置值进行修改.SpringBoot 使用一个名为 application.properties 或者 application.yaml的文件作为全局配置文件, ...
- golang在win10安装、环境配置 和 goland(IDE开发golang配置)
前言 本人在使用goland软件开发go时,对于goland软件配置网上资料少,为了方便自己遗忘.也为了希望和我一样的小白能够更好的使用,所以就写下这篇博客,废话不多说开考. 一.查看自己电脑系统版本 ...
- ASP.NET Core - 配置系统之配置读取
一个应用要运行起来,往往需要读取很多的预设好的配置信息,根据约定好的信息或方式执行一定的行为. 配置的本质就是软件运行的参数,在一个软件实现中需要的参数非常多,如果我们以 Hard Code(硬编码) ...
随机推荐
- compileSdkVersion, minSdkVersion 和 targetSdkVersion,傻傻分不清楚【转】
原文 https://blog.csdn.net/gaolh89/article/details/79809034 在Android Studio项目的app/build.gradle中,我们可以看到 ...
- 【YashanDB知识库】swap空间使用超大报错
问题描述 问题单 使用GROUP_CONCAT函数时,数据库swap表空间上涨厉害 测试用例 drop table tmp1; create table tmp1(c1 int,c2 double,c ...
- AWS Data Analytics Fundamentals 官方课程笔记 - Variety, Veracity, Value
Variety structured data applications include Amazon RDS, Amazon Aurora, MySQL, MariaDB, PostgreSQL, ...
- 把dataframe 一列转成 array
把dataframe 一列转成 array
- PageHeper
PageHelper 是一个非常流行的 MyBatis 分页插件,主要用于简化分页查询的实现.使用 PageHelper 可以在执行数据库查询时,自动处理分页参数,从而避免手动编写繁琐的分页逻辑. 今 ...
- k8s 操作命令(合集List)
k8s 操作命令 合集List 一.K8S最常用命令如下: 1.获取pod信息:kubectl get pod 2.查看指定pod的日志信息:kubectl logs -f --tail(最后多少行) ...
- vue-i18n 8.28.2(完成)
https://kazupon.github.io/vue-i18n/zh/introduction.html 开始 如果使用模块系统 (例如通过 vue-cli),则需要导入 Vue 和 VueI1 ...
- 深入C++引用及其注意事项、对引用取地址时的内存模型、const数组等
const int f[10] = { 1,2,3,4,5,6,7,8,9,10 }; int main() { // test1 const int i = 3; int& j = cons ...
- Java中浮点数运算存在的精度问题以及解决方法
观察以下一段代码,相信小朋友都可以一眼看出答案,但是计算机给出的答案是这样吗? public class TestDouble { public static void main(String arg ...
- 17 模块subprocess、re
1. subprocess模块 1.1 概念 subprocess模块启动一个新进程,并连接到它们的输入/输出/错误管道,从而获取返回值 简单理解:可以远程连接电脑(socket模块) 1.2 Pop ...