Go 語言之 Viper 的使用

来源:https://www.cnblogs.com/QiaoPengjun/archive/2023/06/18/17489207.html
-Advertisement-
Play Games

# Go 語言之 Viper 的使用 ## Viper 介紹 [Viper](https://github.com/spf13/viper): ### 安裝 ```bash go get github.com/spf13/viper ``` ### Viper 是什麼? Viper 是一個針對 Go ...


Go 語言之 Viper 的使用

Viper 介紹

Viperhttps://github.com/spf13/viper

安裝

go get github.com/spf13/viper

Viper 是什麼?

Viper 是一個針對 Go 應用程式的完整配置解決方案,包括12-Factor 應用程式。它可以在應用程式中工作,並且可以處理所有類型的配置需求和格式。它支持:

Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application, and can handle all types of configuration needs and formats. It supports:

  • setting defaults
  • reading from JSON, TOML, YAML, HCL, envfile and Java properties config files
  • live watching and re-reading of config files (optional)
  • reading from environment variables
  • reading from remote config systems (etcd or Consul), and watching changes
  • reading from command line flags
  • reading from buffer
  • setting explicit values

Viper can be thought of as a registry for all of your applications configuration needs.

Viper 可以被認為是滿足所有應用程式配置需求的註冊表。

為什麼使用 Viper?

在構建現代應用程式時,您不需要擔心配置文件格式; 您需要專註於構建令人滿意的軟體。Viper 就是為此而生的。

Viper 可以為你做以下事情:

  1. Find, load, and unmarshal a configuration file in JSON, TOML, YAML, HCL, INI, envfile or Java properties formats.
  2. Provide a mechanism to set default values for your different configuration options.
  3. Provide a mechanism to set override values for options specified through command line flags.
  4. Provide an alias system to easily rename parameters without breaking existing code.
  5. Make it easy to tell the difference between when a user has provided a command line or config file which is the same as the default.

Viper uses the following precedence order. Each item takes precedence over the item below it:

  • explicit call to Set
  • flag
  • env
  • config
  • key/value store
  • default

Important: Viper configuration keys are case insensitive. There are ongoing discussions about making that optional.

重要提示: Viper 配置鍵是不區分大小寫的。目前正在討論是否將其設置為可選的。

Viper 實操 Putting Values into Viper

建立預設值

一個好的配置系統將支持預設值。密鑰不需要預設值,但如果沒有通過配置文件、環境變數、遠程配置或標誌設置密鑰,則預設值非常有用。

Examples:

viper.SetDefault("ContentDir", "content")
viper.SetDefault("LayoutDir", "layouts")
viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})

讀取配置文件

Viper 需要最小的配置,這樣它就知道在哪裡查找配置文件。Viper 支持 JSON、 TOML、 YAML、 HCL、 INI、 envfile 和 JavaProperties 文件。Viper 可以搜索多個路徑,但目前單個 Viper 實例只支持單個配置文件。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))
}

您可以處理沒有如下配置文件的特定情況:

if err := viper.ReadInConfig(); err != nil {
	if _, ok := err.(viper.ConfigFileNotFoundError); ok {
		// Config file not found; ignore error if desired
	} else {
		// Config file was found but another error was produced
	}
}

// Config file found and successfully parsed

寫入配置文件

從配置文件中讀取是有用的,但有時您希望存儲在運行時所做的所有修改。為此,提供了一系列命令,每個命令都有自己的用途:

  • WriteConfig-將當前 viper 配置寫入預定義的路徑(如果存在)。如果沒有預定義的路徑就會出錯。將覆蓋當前配置文件(如果存在)。
  • SafeWriteConfig-將當前 viper 配置寫入預定義的路徑。如果沒有預定義的路徑就會出錯。不會覆蓋當前配置文件(如果存在)。
  • WriteConfigAs-將當前 viper 配置寫入給定的文件路徑。將覆蓋給定的文件(如果存在)。
  • SafeWriteConfigAs-將當前 viper 配置寫入給定的文件路徑。不會覆蓋給定的文件(如果存在)。

As a rule of the thumb, everything marked with safe won't overwrite any file, but just create if not existent, whilst the default behavior is to create or truncate.

根據經驗,所有標記為 safe 的文件都不會覆蓋任何文件,只是創建(如果不存在的話) ,而預設行為是創建或截斷。

A small examples section:

viper.WriteConfig() // writes current config to predefined path set by 'viper.AddConfigPath()' and 'viper.SetConfigName'
viper.SafeWriteConfig()
viper.WriteConfigAs("/path/to/my/.config")
viper.SafeWriteConfigAs("/path/to/my/.config") // will error since it has already been written
viper.SafeWriteConfigAs("/path/to/my/.other_config")

監視和重新讀取配置文件

Viper 支持讓應用程式在運行時實時讀取配置文件的能力。

需要重新啟動伺服器才能使配置生效的日子已經一去不復返了,使用 viper 的應用程式可以在運行時讀取配置文件的更新,而且不會錯過任何一次更新。

只需告訴 viper 實例監視 Config。您還可以為 Viper 提供一個函數,以便在每次發生更改時運行該函數。

確保在調用 WatchConfig ()之前添加了所有的 configPath

viper.OnConfigChange(func(e fsnotify.Event) {
	fmt.Println("Config file changed:", e.Name)
})
viper.WatchConfig()

配置文件實時載入實操

package main

import (
	"fmt"
	"net/http"

	"github.com/fsnotify/fsnotify"
	"github.com/gin-gonic/gin"

	"github.com/spf13/viper"
)

func main() {
	// 設置預設值
	viper.SetDefault("fileDir", "./")
	// 讀取配置文件
	viper.SetConfigFile("./config.yaml")  // 指定配置文件路徑
	viper.SetConfigName("config")         // 配置文件名稱(無擴展名)
	viper.SetConfigType("yaml")           // 如果配置文件的名稱中沒有擴展名,則需要配置此項
	viper.AddConfigPath("/etc/appname/")  // 查找配置文件所在的路徑
	viper.AddConfigPath("$HOME/.appname") // 多次調用以添加多個搜索路徑
	viper.AddConfigPath(".")              // 還可以在工作目錄中查找配置

	err := viper.ReadInConfig() // 查找並讀取配置文件
	if err != nil {             // 處理讀取配置文件的錯誤
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}

	// 實時監控配置文件的變化 WatchConfig 開始監視配置文件的更改。
	viper.WatchConfig()
	// OnConfigChange設置配置文件更改時調用的事件處理程式。
	// 當配置文件變化之後調用的一個回調函數
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
	})

	r := gin.Default()
	r.GET("/version", func(c *gin.Context) {
		// GetString以字元串的形式返回與鍵相關的值。
		c.String(http.StatusOK, viper.GetString("version"))
	})
	r.Run()
}

運行並訪問:http://127.0.0.1:8080/version

Code/go/viper_demo via 

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • # Go 語言之 Shutdown 關機和fvbock/endless 重啟 Shutdown 源碼 ```go // Shutdown gracefully shuts down the server without interrupting any // active connections. ...
  • **描述** 給定一個非負整數數組,統計裡面每一個數的出現次數。我們只統計到數組裡最大的數。 假設 Fmax (Fmax using namespace std; int main(){ int n,x; int fmax=0;//數組裡最大的數 int a[10000]={0}; cin>>n; ...
  • 某日二師兄參加XXX科技公司的C++工程師開發崗位第18面: > 面試官:`std::string`用過吧? > > 二師兄:當然用過(廢話,C++程式員就沒有沒用過`std::string`的)。 > > 面試官:`std::string("hello")+"world"`、`"hello"+st ...
  • 使用 QCustomPlot 繪圖庫輔助開發時整理的學習筆記。本篇介紹 QCustomPlot 的一種使用方法,通過包含源碼的方式進行使用,這也是最常用的方法,示例中使用的 QCustomPlot 版本為 Version 2.1.1。 ...
  • # Java 變數與基本數據類型 # 1. 變數是保存特定數據類型的值。變數必須先聲明,後使用。變數表示記憶體中的一個存儲區域。變數在同一個域中不可出現相同的變數名。 ## # 2. 程式中 + 號的作用 > ## 如果兩邊都是數值,進行加法運算 > > ## 如果左右一邊有一方位字元串,則做拼接字元 ...
  • > 我們之前對Redis的學習都是在命令行視窗,那麼如何使用Java來對Redis進行操作呢?對於Java連接Redis的開發工具有很多,這裡先介紹通過Jedis實現對Redis的各種操作。(前提是你的redis已經配置了遠程訪問) ## 1.創建一個maven工程,並且添加以下依賴 ~~~xml ...
  • 利用Python調用外部系統命令的方法可以提高編碼效率。調用外部系統命令完成後可以通過獲取命令執行返回結果碼、命令執行的輸出結果進行進一步的處理。本文主要描述Python常見的調用外部系統命令的方法,包括os.system()、os.popen()、subprocess.Popen()等。 本文分析 ...
  • pymongo模塊是python操作mongo數據的第三方模塊,記錄一下常用到的簡單用法。 **首先需要連接資料庫:** - MongoClient():該方法第一個參數是資料庫所在地址,第二個參數是資料庫所在的埠號 - authenticate():該方法第一個參數是資料庫的賬號,第二個參數是數 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...