美文网首页
Go语言配置管理神器——Viper中文教程

Go语言配置管理神器——Viper中文教程

作者: hsiaojun | 来源:发表于2020-06-11 09:36 被阅读0次

    参考链接:https://www.liwenzhou.com/posts/Go/viper_tutorial/

    什么是Viper?

    Viper是适用于Go应用程序(包括Twelve-Factor App)的完整配置解决方案。它被设计用于在应用程序中工作,并且可以处理所有类型的配置需求和格式。它支持以下特性:

    • 设置默认值
    • 从JSON、TOML、YAML、HCL、envfile和Java properties格式- 的配置文件读取配置信息实时监控和重新读取配置文件(可选)
    • 从环境变量中读取
    • 从远程配置系统(etcd或Consul)读取并监控配置变化
    • 从命令行参数读取配置
    • 从buffer读取配置
    • 显式配置值

    下载

    go get github.com/spf13/viper
    

    例子

    package main
    
    import (
        "fmt"
        "github.com/gin-gonic/gin"
        "github.com/spf13/viper"
    )
    
    func main(){
        viper.SetConfigName("config")  # 配置文件名
        viper.SetConfigType("yaml") # 配置文件类型,可以是yaml、json、xml。。。
        viper.AddConfigPath(".")  # 配置文件路径
        err := viper.ReadInConfig()  # 读取配置文件信息
        if err != nil{
            panic(fmt.Errorf("Fatal error config file: %s \n", err))
        }
    
        r := gin.Default()
        if err := r.Run(fmt.Sprintf(":%d", viper.Get("port"))); err != nil {
            panic(err)
        }
    }
    

    .config.yaml文件内容如下:

    port: 9999
    

    运行结果:


    image.png

    相关文章

      网友评论

          本文标题:Go语言配置管理神器——Viper中文教程

          本文链接:https://www.haomeiwen.com/subject/giuvtktx.html