golang如何通过viper读取config.yaml文件
目录
1.导入依赖包2.编写yaml文件3.编写读取yaml文件的go文件4.使用config对象5.viper源码分析1.导入依赖包
import ( "github.com/spf13/viper" )
2.编写yaml文件
放在conf目录下,文件名叫config.yaml
# TODO 本地调试时放开 KubeSphere_URL: http://192.168.103.48:3188 # TODO 部署到环境时放开 #KubeSphere_URL: http://ks-apiserver.kubesphere-system.svc:80 KubesphereAdminUser: admin KubespherePassword: Admin123 #TODO 调用梅姐服务的ip,暂用当前,后续需要修改 Other_service_IP: http://192.168.103.48:30412 #Other_service_IP: http://container-cloud-system-controller-manager-metrics-service.container-cloud-system-system.svc:8093 Other_service_URL: /capis/quota.ictnj.io/v1alpha1/namespaces/ #TODO harbor镜像仓库地址 HARBOR_URL: https://192.168.66.4:443 HARBOR_ADMIN_USERNAME: admin HARBOR_ADMIN_PASSWD: Harbor12345 HARBOR_IP_HTTPS: 192.168.66.4:443 HARBOR_SSH_ADDRESS: 192.168.103.48:53304 HARBOR_SSH_USERNAME: root HARBOR_SSH_PASSWD: peng123.
3.编写读取yaml文件的go文件
放在config目录下,文件名叫config.go
需要注意的是目录的问题,如果放在同目录,直接用configurationPath,不同的编辑器,
vscode跟golang对相对路径处理不同
package config
import (
"github.com/spf13/viper"
)
const (
configurationName = "config"
configurationPath = "./conf"
// vscode特殊读取路径
// configurationPath_vscode = "../conf"
)
var Config *viper.Viper
func init() {
Config = viper.New()
Config.SetConfigName(configurationName)
Config.AddConfigPath(configurationPath)
Config.SetConfigType("yaml")
Config.AddConfigPath(configurationPath)
if err := config.ReadInConfig(); err != nil {
panic(err)
}
}如果config.yaml跟config.go放在同目录简单的路径用上面这个,如果路径不同,且不同的同事用不同的编译软件,可以尝试下面的路径兼容
package config
import (
"github.com/spf13/viper"
)
const (
configurationName = "config"
configurationPath = "./conf"
// vscode特殊读取路径
configurationPath_vscode = "../conf"
)
var Config *viper.Viper
func init() {
Config = viper.New()
Config.SetConfigName(configurationName)
Config.AddConfigPath(configurationPath)
Config.SetConfigType("yaml")
if err := Config.ReadInConfig(); err != nil {
Config.AddConfigPath(configurationPath_vscode)
if err := Config.ReadInConfig(); err != nil {
Config.AddConfigPath(configurationPath)
panic(err)
}
}
}4.使用config对象
Config.GetString("KubeSphere_URL")5.viper源码分析
type Viper struct {
// Delimiter that separates a list of keys
// used to access a nested value in one go
keyDelim string
// A set of paths to look for the config file in
configPaths []string
// The filesystem to read config from.
fs afero.Fs
// A set of remote providers to search for the configuration
remoteProviders []*defaultRemoteProvider
// Name of file to look for inside the path
configName string
configFile string
configType string
configPermissions os.FileMode
envPrefix string
automaticEnvApplied bool
envKeyReplacer StringReplacer
allowEmptyEnv bool
config map[string]interface{}
override map[string]interface{}
defaults map[string]interface{}
kvstore map[string]interface{}
pflags map[string]FlagValue
env map[string]string
aliases map[string]string
typeByDefValue bool
// Store read properties on the object so that we can write back in order with comments.
// This will only be used if the configuration read is a properties file.
properties *properties.Properties
onConfigChange func(fsnotify.Event)
}func (v *Viper) ReadInConfig() error {
jww.INFO.Println("Attempting to read in config file")
filename, err := v.getConfigFile()
if err != nil {
return err
}
if !stringInSlice(v.getConfigType(), SupportedExts) {
return UnsupportedConfigError(v.getConfigType())
}
jww.DEBUG.Println("Reading file: ", filename)
file, err := afero.ReadFile(v.fs, filename)
if err != nil {
return err
}
config := make(map[string]interface{})
err = v.unmarshalReader(bytes.NewReader(file), config)
if err != nil {
return err
}
v.config = config
return nil
}把yaml文件的键值读取到viper对象的config当中
到此这篇关于golang如何通过viper读取config.yaml文件的文章就介绍到这了,更多相关golang读取config.yaml内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
上一篇:C++实现简单学生管理系统
X 关闭
X 关闭
- 15G资费不大降!三大运营商谁提供的5G网速最快?中国信通院给出答案
- 2联想拯救者Y70发布最新预告:售价2970元起 迄今最便宜的骁龙8+旗舰
- 3亚马逊开始大规模推广掌纹支付技术 顾客可使用“挥手付”结账
- 4现代和起亚上半年出口20万辆新能源汽车同比增长30.6%
- 5如何让居民5分钟使用到各种设施?沙特“线性城市”来了
- 6AMD实现连续8个季度的增长 季度营收首次突破60亿美元利润更是翻倍
- 7转转集团发布2022年二季度手机行情报告:二手市场“飘香”
- 8充电宝100Wh等于多少毫安?铁路旅客禁止、限制携带和托运物品目录
- 9好消息!京东与腾讯续签三年战略合作协议 加强技术创新与供应链服务
- 10名创优品拟通过香港IPO全球发售4100万股 全球发售所得款项有什么用处?

