脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Golang - golang如何通过viper读取config.yaml文件

golang如何通过viper读取config.yaml文件

2022-09-07 10:16峰啊疯了 Golang

这篇文章主要介绍了golang通过viper读取config.yaml文件,围绕golang读取config.yaml文件的相关资料展开详细内容,需要的小伙伴可以参考一下

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对相对路径处理不同

golang如何通过viper读取config.yaml文件

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对象

golang如何通过viper读取config.yaml文件

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
}

golang如何通过viper读取config.yaml文件

把yaml文件的键值读取到viper对象的config当中

到此这篇关于golang如何通过viper读取config.yaml文件的文章就介绍到这了,更多相关golang读取config.yaml内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文地址:https://blog.51cto.com/u_12040959/5098392

延伸 · 阅读

精彩推荐
  • GolangGoAdminGroup/go-admin的安装和运行的教程详解

    GoAdminGroup/go-admin的安装和运行的教程详解

    这篇文章主要介绍了GoAdminGroup/go-admin的安装和运行的教程详解,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需...

    陶士涵5942020-09-30
  • GolangGo语言interface详解

    Go语言interface详解

    这篇文章主要介绍了Go语言interface详解,本文讲解了什么是interface、interface类型、interface值、空interface、interface函数参数等内容,需要的朋友可以参考下 ...

    junjie3972020-04-09
  • Golanggolang grpc 负载均衡的方法

    golang grpc 负载均衡的方法

    这篇文章主要介绍了golang grpc 负载均衡的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧 ...

    xjtuhit4252020-05-16
  • Golang利用Golang实现TCP连接的双向拷贝详解

    利用Golang实现TCP连接的双向拷贝详解

    公司中遇到了一个使用golang编写的agent程序,所以这篇文章主要给大家介绍了关于利用Go如何实现TCP连接的双向拷贝的相关资料,文中通过示例代码介绍的非...

    陶文3162020-05-09
  • GolangGolang中使用JSON的一些小技巧分享

    Golang中使用JSON的一些小技巧分享

    这篇文章主要分享了Golang中使用JSON的一些小技巧,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来一起看看吧。...

    daisy6042020-05-07
  • GolangGolang实现Directional Channel(定向通道)

    Golang实现Directional Channel(定向通道)

    这篇文章主要介绍了Golang实现Directional Channel(定向通道),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友...

    L1ng147252021-03-28
  • Golang一例 Go 编译器代码优化 bug 定位和修复解析

    一例 Go 编译器代码优化 bug 定位和修复解析

    本文中介绍了 Go 编译器的整体编译流程脉络和一个编译优化错误导致数据越界访问的 bug,并分析了对这个 bug 的排查和修复过程,希望能够借此让大家对...

    今日头条1972020-11-10
  • GolangGolang中的int类型和uint类型到底有多大?

    Golang中的int类型和uint类型到底有多大?

    int和uint类型在我们日常开发中经常会用到,但有个疑问就是这两个类型有多大,通过各种尝试最终得到了答案,所以下面这篇文章主要给大家介绍了关于...

    cyeam9582020-05-12