SoFunction
Updated on 2025-03-02

golang uses viper to read custom configuration files

viper supports Yaml, Json, TOML, HCL and other formats, and is very convenient to read.

There are cases on the viper official website:/spf13/viper

go get /spf13/viper

Create a file

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

Create a configuration file for initializing

func InitConfig() {
  path, err := ()
  if err != nil {
    panic(err)
  }
  (path + "/config/dev")
  ("config")
  ("yaml")
  if err := (); err != nil {
    panic(err)
  }
}

Simple use:

  username := ("")
  password := ("")
  host := ("")
  port := ("")
  dbname := ("")
  dsn := ("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",username,password,host, port, dbname)
  GormPool, err = ("mysql", dsn)

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.