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

作者:峰啊疯了 时间:2023-07-22 05:46:11 

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当中

来源:https://blog.51cto.com/u_12040959/5098392

标签:golang,viper,读取,config.yaml
0
投稿

猜你喜欢

  • Mac下mysql5.7.10安装教程

    2024-01-20 15:50:07
  • go常用指令之go mod详解

    2024-04-23 09:49:09
  • python的类class定义及其初始化方式

    2023-08-07 11:52:15
  • pytorch中图像的数据格式实例

    2021-02-16 06:22:19
  • 很有意思的SQL多行数据拼接

    2024-01-28 02:08:56
  • 得到自增列的下一个会插入的id

    2024-01-20 17:32:48
  • eWebEditor 上传文件提示格式不正确的解决方法

    2022-10-08 03:21:51
  • PHP结合vue导出excel出现乱码的解决方法分享

    2023-05-30 09:18:25
  • Vue项目中如何使用Axios封装http请求详解

    2024-04-28 09:19:49
  • Jupyter安装拓展nbextensions及解决官网下载慢的问题

    2023-11-24 20:50:54
  • virtualenv介绍及简明教程

    2023-07-04 08:46:33
  • JQuery获取表单值

    2009-11-19 13:17:00
  • Python如何实现自动发送邮件

    2022-05-09 04:22:55
  • SQL的小常识, 备忘之用, 慢慢补充.

    2011-11-03 17:19:45
  • 网页设计中HTML常范的五个错误

    2008-04-22 18:14:00
  • 灵活运用Python 枚举类来实现设计状态码信息

    2023-04-29 15:03:34
  • mysql_connect(): Connection using old (pre-4.1.1) authentication protocol refused

    2024-01-23 08:22:11
  • python request要求接口参数必须是json数据的处理方式

    2023-07-14 03:12:18
  • 鼠标右击事件代码(asp.net后台)

    2024-04-19 10:07:32
  • 一文详解如何用GPU来运行Python代码

    2022-02-26 17:49:30
  • asp之家 网络编程 m.aspxhome.com