当前位置 博文首页 > golang 使用 viper 读取自定义配置文件

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

    作者:代码的坏味道 时间:2021-02-18 09:44

    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)
    
    
    js