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内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!