Golang-Viper读取配置文件

2024-03-29 09:20

本文主要是介绍Golang-Viper读取配置文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

为什么需要配置文件

  1. 代码可维护性
  2. 不用修改配置重启服务

安装

go get -u github.com/spf13/viper

代码示例

结构体Server配置

type Server struct {JWT     JWT     `mapstructure:"jwt" json:"jwt" yaml:"jwt"`Redis   Redis   `mapstructure:"redis" json:"redis" yaml:"redis"`Email   Email   `mapstructure:"email" json:"email" yaml:"email"`Captcha Captcha `mapstructure:"captcha" json:"captcha" yaml:"captcha"`// gormMysql Mysql `mapstructure:"mysql" json:"mysql" yaml:"mysql"`// ossTencentCOS TencentCOS `mapstructure:"tencent-cos" json:"tencent-cos" yaml:"tencent-cos"`// 跨域配置Cors CORS `mapstructure:"cors" json:"cors" yaml:"cors"`
}

JWT

type JWT struct {SigningKey  string `mapstructure:"signing-key" json:"signing-key" yaml:"signing-key"`    // jwt签名ExpiresTime string `mapstructure:"expires-time" json:"expires-time" yaml:"expires-time"` // 过期时间BufferTime  string `mapstructure:"buffer-time" json:"buffer-time" yaml:"buffer-time"`    // 缓冲时间Issuer      string `mapstructure:"issuer" json:"issuer" yaml:"issuer"`                   // 签发者
}

Redis

type Redis struct {Addr     string `mapstructure:"addr" json:"addr" yaml:"addr"`             // 服务器地址:端口Password string `mapstructure:"password" json:"password" yaml:"password"` // 密码DB       int    `mapstructure:"db" json:"db" yaml:"db"`                   // redis的哪个数据库
}

邮箱配置

type Email struct {To       string `mapstructure:"to" json:"to" yaml:"to"`                   // 收件人:多个以英文逗号分隔 例:a@qq.com b@qq.com 正式开发中请把此项目作为参数使用From     string `mapstructure:"from" json:"from" yaml:"from"`             // 发件人  你自己要发邮件的邮箱Host     string `mapstructure:"host" json:"host" yaml:"host"`             // 服务器地址 例如 smtp.qq.com  请前往QQ或者你要发邮件的邮箱查看其smtp协议Secret   string `mapstructure:"secret" json:"secret" yaml:"secret"`       // 密钥    用于登录的密钥 最好不要用邮箱密码 去邮箱smtp申请一个用于登录的密钥Nickname string `mapstructure:"nickname" json:"nickname" yaml:"nickname"` // 昵称    发件人昵称 通常为自己的邮箱Port     int    `mapstructure:"port" json:"port" yaml:"port"`             // 端口     请前往QQ或者你要发邮件的邮箱查看其smtp协议 大多为 465IsSSL    bool   `mapstructure:"is-ssl" json:"is-ssl" yaml:"is-ssl"`       // 是否SSL   是否开启SSL
}

验证码配置

type Captcha struct {KeyLong            int `mapstructure:"key-long" json:"key-long" yaml:"key-long"`                                     // 验证码长度ImgWidth           int `mapstructure:"img-width" json:"img-width" yaml:"img-width"`                                  // 验证码宽度ImgHeight          int `mapstructure:"img-height" json:"img-height" yaml:"img-height"`                               // 验证码高度OpenCaptcha        int `mapstructure:"open-captcha" json:"open-captcha" yaml:"open-captcha"`                         // 防爆破验证码开启此数,0代表每次登录都需要验证码,其他数字代表错误密码此数,如3代表错误三次后出现验证码OpenCaptchaTimeOut int `mapstructure:"open-captcha-timeout" json:"open-captcha-timeout" yaml:"open-captcha-timeout"` // 防爆破验证码超时时间,单位:s(秒)
}

数据库配置

type Mysql struct {Prefix       string `mapstructure:"prefix" json:"prefix" yaml:"prefix"`Port         string `mapstructure:"port" json:"port" yaml:"port"`Config       string `mapstructure:"config" json:"config" yaml:"config"`       // 高级配置Dbname       string `mapstructure:"db-name" json:"db-name" yaml:"db-name"`    // 数据库名Username     string `mapstructure:"username" json:"username" yaml:"username"` // 数据库密码Password     string `mapstructure:"password" json:"password" yaml:"password"` // 数据库密码Path         string `mapstructure:"path" json:"path" yaml:"path"`Engine       string `mapstructure:"engine" json:"engine" yaml:"engine" default:"InnoDB"`        //数据库引擎,默认InnoDBLogMode      string `mapstructure:"log-mode" json:"log-mode" yaml:"log-mode"`                   // 是否开启Gorm全局日志MaxIdleConns int    `mapstructure:"max-idle-conns" json:"max-idle-conns" yaml:"max-idle-conns"` // 空闲中的最大连接数MaxOpenConns int    `mapstructure:"max-open-conns" json:"max-open-conns" yaml:"max-open-conns"` // 打开到数据库的最大连接数Singular     bool   `mapstructure:"singular" json:"singular" yaml:"singular"`                   //是否开启全局禁用复数,true表示开启LogZap       bool   `mapstructure:"log-zap" json:"log-zap" yaml:"log-zap"`
}
func (m *Mysql) Dsn() string {return m.Username + ":" + m.Password + "@tcp(" + m.Path + ":" + m.Port + ")/" + m.Dbname + "?" + m.Config
}func (m *Mysql) GetLogMode() string {return m.LogMode
}

COS云对象存储配置

type TencentCOS struct {Bucket     string `mapstructure:"bucket" json:"bucket" yaml:"bucket"`Region     string `mapstructure:"region" json:"region" yaml:"region"`SecretID   string `mapstructure:"secret-id" json:"secret-id" yaml:"secret-id"`SecretKey  string `mapstructure:"secret-key" json:"secret-key" yaml:"secret-key"`BaseURL    string `mapstructure:"base-url" json:"base-url" yaml:"base-url"`PathPrefix string `mapstructure:"path-prefix" json:"path-prefix" yaml:"path-prefix"`
}
type CORS struct {Mode      string          `mapstructure:"mode" json:"mode" yaml:"mode"`Whitelist []CORSWhitelist `mapstructure:"whitelist" json:"whitelist" yaml:"whitelist"`
}

跨域配置

type CORSWhitelist struct {AllowOrigin      string `mapstructure:"allow-origin" json:"allow-origin" yaml:"allow-origin"`AllowMethods     string `mapstructure:"allow-methods" json:"allow-methods" yaml:"allow-methods"`AllowHeaders     string `mapstructure:"allow-headers" json:"allow-headers" yaml:"allow-headers"`ExposeHeaders    string `mapstructure:"expose-headers" json:"expose-headers" yaml:"expose-headers"`AllowCredentials bool   `mapstructure:"allow-credentials" json:"allow-credentials" yaml:"allow-credentials"`
}

Viper读取yaml配置文件

const (ConfigEnv         = "GVA_CONFIG"ConfigDefaultFile = "config.yaml"ConfigTestFile    = "config.test.yaml"ConfigDebugFile   = "config.debug.yaml"ConfigReleaseFile = "config.release.yaml"
)
func Viper(path ...string) *viper.Viper {var configFile stringif len(path) == 0 {flag.StringVar(&configFile, "c", "", "choose config file.")flag.Parse()if configFile == "" { // 判断命令行参数是否为空switch gin.Mode() {case gin.DebugMode:configFile = ConfigDefaultFilefmt.Printf("您正在使用gin模式的%s环境名称,config的路径为%s\n", gin.Mode())case gin.ReleaseMode:configFile = ConfigReleaseFilefmt.Printf("您正在使用gin模式的%s环境名称,config的路径为", gin.Mode())case gin.TestMode:configFile = ConfigTestFilefmt.Printf("您正在使用gin模式的%s环境名称,config的路径为%s\n", gin.Mode())}} else { // 命令行参数不为空 将值赋值于configfmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%s\n", configFile)}} else { // 函数传递的可变参数的第一个值赋值于configconfigFile = path[0]fmt.Printf("您正在使用func Viper()传递的值,config的路径为%s\n", configFile)}// 初始化Viper對象v := viper.New()// 设置配置文件的路径v.SetConfigFile(configFile)// 配置文件类型v.SetConfigType("yaml")err := v.ReadInConfig()if err != nil {panic(fmt.Errorf("Fatal error config file: %s \n", err))}// 配置文件变动会重读不必重启服务v.WatchConfig()// 当配置文件变化调用此hook 确保在调用之前添加所有 configPathv.OnConfigChange(func(e fsnotify.Event) {fmt.Println("config file changed:", e.Name)if err = v.Unmarshal(&GVA_CONFIG); err != nil {fmt.Println(err)}})if err = v.Unmarshal(&GVA_CONFIG); err != nil {panic(err)}return v
}

// 在其他文件中

v := cofnig.Viper()
v.get("mysql")

在这里插入图片描述

这篇关于Golang-Viper读取配置文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/858215

相关文章

Golang HashMap实现原理解析

《GolangHashMap实现原理解析》HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持高效的插入、查找和删除操作,:本文主要介绍GolangH... 目录HashMap是一种基于哈希表实现的键值对存储结构,它通过哈希函数将键映射到数组的索引位置,支持

如何使用 Python 读取 Excel 数据

《如何使用Python读取Excel数据》:本文主要介绍使用Python读取Excel数据的详细教程,通过pandas和openpyxl,你可以轻松读取Excel文件,并进行各种数据处理操... 目录使用 python 读取 Excel 数据的详细教程1. 安装必要的依赖2. 读取 Excel 文件3. 读

Spring Boot读取配置文件的五种方式小结

《SpringBoot读取配置文件的五种方式小结》SpringBoot提供了灵活多样的方式来读取配置文件,这篇文章为大家介绍了5种常见的读取方式,文中的示例代码简洁易懂,大家可以根据自己的需要进... 目录1. 配置文件位置与加载顺序2. 读取配置文件的方式汇总方式一:使用 @Value 注解读取配置方式二

基于Python实现读取嵌套压缩包下文件的方法

《基于Python实现读取嵌套压缩包下文件的方法》工作中遇到的问题,需要用Python实现嵌套压缩包下文件读取,本文给大家介绍了详细的解决方法,并有相关的代码示例供大家参考,需要的朋友可以参考下... 目录思路完整代码代码优化思路打开外层zip压缩包并遍历文件:使用with zipfile.ZipFil

python3 gunicorn配置文件的用法解读

《python3gunicorn配置文件的用法解读》:本文主要介绍python3gunicorn配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python3 gunicorn配置文件配置文件服务启动、重启、关闭启动重启关闭总结python3 gun

golang获取当前时间、时间戳和时间字符串及它们之间的相互转换方法

《golang获取当前时间、时间戳和时间字符串及它们之间的相互转换方法》:本文主要介绍golang获取当前时间、时间戳和时间字符串及它们之间的相互转换,本文通过实例代码给大家介绍的非常详细,感兴趣... 目录1、获取当前时间2、获取当前时间戳3、获取当前时间的字符串格式4、它们之间的相互转化上篇文章给大家介

Spring Boot 配置文件之类型、加载顺序与最佳实践记录

《SpringBoot配置文件之类型、加载顺序与最佳实践记录》SpringBoot的配置文件是灵活且强大的工具,通过合理的配置管理,可以让应用开发和部署更加高效,无论是简单的属性配置,还是复杂... 目录Spring Boot 配置文件详解一、Spring Boot 配置文件类型1.1 applicatio

golang 日志log与logrus示例详解

《golang日志log与logrus示例详解》log是Go语言标准库中一个简单的日志库,本文给大家介绍golang日志log与logrus示例详解,感兴趣的朋友一起看看吧... 目录一、Go 标准库 log 详解1. 功能特点2. 常用函数3. 示例代码4. 优势和局限二、第三方库 logrus 详解1.

SpringBoot3使用Jasypt实现加密配置文件

《SpringBoot3使用Jasypt实现加密配置文件》这篇文章主要为大家详细介绍了SpringBoot3如何使用Jasypt实现加密配置文件功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编... 目录一. 使用步骤1. 添加依赖2.配置加密密码3. 加密敏感信息4. 将加密信息存储到配置文件中5

解决Java中基于GeoTools的Shapefile读取乱码的问题

《解决Java中基于GeoTools的Shapefile读取乱码的问题》本文主要讨论了在使用Java编程语言进行地理信息数据解析时遇到的Shapefile属性信息乱码问题,以及根据不同的编码设置进行属... 目录前言1、Shapefile属性字段编码的情况:一、Shp文件常见的字符集编码1、System编码