golang 使用 viper 读取自定义配置文件

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

golang 使用 viper 读取自定义配置文件

  2021-04-02 我要评论

viper 支持 Yaml、Json、 TOML、HCL 等格式,读取非常的方便。

viper 官网有案例:https://github.com/spf13/viper

go get github.com/spf13/viper

创建 config.yaml 文件

database:
 driver: mysql
 host: 127.0.0.1
 port: 3306
 username: blog
 dbname: blog
 password: 123456

建一个 config.go 用于初始化配置文件

func InitConfig() {
  path, err := os.Getwd()
  if err != nil {
    panic(err)
  }
  viper.AddConfigPath(path + "/config/dev")
  viper.SetConfigName("config")
  viper.SetConfigType("yaml")
  if err := viper.ReadInConfig(); err != nil {
    panic(err)
  }
}

简单使用:

  username := viper.GetString("database.username")
  password := viper.GetString("database.password")
  host := viper.GetString("database.host")
  port := viper.GetInt("database.port")
  dbname := viper.GetString("database.dbname")
  dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",username,password,host, port, dbname)
  GormPool, err = gorm.Open("mysql", dsn)

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们