跳至主要内容

專案配置管理工具 Viper

Viper 概論

Viper 是適用於 Go 專案的開發工具,在 Go 社群中被廣泛使用。Viper提供簡單且統一的方式處理應用程式的配置,並支援多種配置源(如檔案、環境變數、命令列參數、遠端配置服務等)。

以下是 Viper 的主要功能及特點:

配置解析

Viper 支援解析多種配置格式,包括 JSON、YAML、TOML、HCL、INI 等,
開發者可根據需求選擇合適的配置格式。

多配置源

Viper 可從不同的配置源中讀取配置,包括檔案系統、環境變數、命令列參數、遠端配置服務等。
開發者可在不同環境下(如開發、測試、生產)輕鬆管理或切換配置。

預設值

Viper 支援設定配置的預設值,如果某個配置項目沒有明確設定,則回傳預設值,
如此可減少代碼中對於配置值的判斷和處理。

監聽變化

Viper 可以監聽配置的變化,開發者若有事先註冊回調函式,
當配置變更時就會執行相應的操作,這對於動態更新配置非常有用。

針對不同需求的子配置

Viper 支援將配置進行分組和層次化,使開發者可根據需要使用子配置,
以利組織或管理配置。

安裝 Viper

GitHub Viper

從 GitHub 找到 Viper 的安裝指令: $ go get github.com/spf13/viper

使用 Viper

參考官方範例編寫設定檔

viper.SetConfigName("config") // name of config file (without extension)
viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
viper.AddConfigPath("/etc/appname/") // path to look for the config file in
viper.AddConfigPath("$HOME/.appname") // call multiple times to add many search paths
viper.AddConfigPath(".") // optionally look for config in the working directory
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
panic(fmt.Errorf("fatal error config file: %w", err))
}