golang USES viper to read from the definition configuration file

  • 2020-09-16 07:30:37
  • OfStack

viper support Yaml, Json, TOML, HCL and other formats, read very convenient.

viper website with case: https: / / github com/spf13 / viper


go get github.com/spf13/viper

Create the config.yaml file


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

Create an ES23en.go to initialize the configuration file


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

Simple use:


  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)


Related articles: