golang use custom configuration files to read viper

viper support Yaml, Json, TOML, HCL and other formats, reading is very convenient.
Download viper

go get github.com/spf13/viper

Create a file config.yaml

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

Build a config.go for initial 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 to 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)

There is a problem, you can add micro letter: cfun666, go into the language learning exchange group

Published 43 original articles · won praise 10 · views 70000 +

Guess you like

Origin blog.csdn.net/cfun_goodmorning/article/details/103942299