Go Viper库

1 min

:rabbit2: GO_配置管理库——Viper

1. 撰写配置文件

mysql:
    host: localhost
    port: 3306
    username: xxx
    password: xxx
    database: xxx

2. Viper 初始化

在根目录新建setting文件夹

  • 建立setting.go文件

    :deciduous_tree:init函数

    每个包可以包含任意多个init函数,它们在程序启动时按照它们在代码中出现的顺序被调用。

    • 在Go语言中,init函数是一个特殊的函数,它在每个Go程序运行前自动被执行。

    • 在Go语言中,如果一个包没有被其他的代码导入,那么它的init函数就不会被执行。所以要在main包中导入

      import (
       _ "github.com/yourusername/yourproject/setting" // 加个下划线表示导入但不使用
      )
      package setting
      
      import (
      	"github.com/spf13/viper"
      	"log"
      )
      
      func init() {
      	viper.SetConfigName("config")
      	viper.SetConfigType("yaml")
      	viper.AddConfigPath("./conf")
      	if err := viper.ReadInConfig(); err != nil {
      		log.Fatalf("Fail to parse 'conf/config.yml': %v", err)
      	}
      }
  • 如果在配置文件(例如 YAML 文件)中手动写入了配置信息,那么就不需要使用 viper.SetDefault 函数来设置默认值

3. 调用配置文件

  • viper包中的Get函数就可以获得数据

    MySQLDSN = fmt.Sprintf("%s:%s@tcp(%s:%s)/diting?charset=utf8mb4&parseTime=True&loc=Local", viper.GetString("mysql.username"), viper.GetString("mysql.password"), viper.GetString("mysql.host"), viper.GetString("mysql.port"))