go配置管理框架viper常用操作
更新時間:2025年04月27日 08:56:39 作者:Wenhao.
這篇文章主要介紹了go配置管理框架viper常用操作,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
官網(wǎng)地址:
GitHub - spf13/viper: Go configuration with fangs
常用操作:
Viper會按照下面的優(yōu)先級。每個項目的優(yōu)先級都高于它下面的項目:
- 顯示調(diào)用
Set
設置值 - 命令行參數(shù)(flag)
- 環(huán)境變量
- 配置文件
- key/value存儲
- 默認值
配置文件 config.yaml
(當前目錄下)
host: "0.0.0.0" mysql: host: "127.0.0.1" port: 3306 cache: cache1: max-items: 100 item-size: 64 cache2: max-items: 200 item-size: 80
配置
viper.SetDefault("redis.port", "localhost:6379") // viper.SetConfigFile("./config.yaml") // 配置文件路徑,此行和下面兩行效果相同 viper.SetConfigName("config") // 配置文件名 viper.SetConfigType("yaml") // 配置文件類型 viper.AddConfigPath("./") // 配置文件路徑 err := viper.ReadInConfig() // 查找并讀取配置文件 if err != nil { panic(fmt.Errorf("fatal error config file: %w", err)) // 處理錯誤 }
從Viper獲取值
在Viper中,有幾種方法可以根據(jù)值的類型獲取值。存在以下功能和方法:
- Get(key string) : interface{}
- GetBool(key string) : bool
- GetFloat64(key string) : float64
- GetInt(key string) : int
- GetIntSlice(key string) : []int
- GetString(key string) : string
- GetStringMap(key string) : map[string]interface{}
- GetStringMapString(key string) : map[string]string
- GetStringSlice(key string) : []string
- GetTime(key string) : time.Time
- GetDuration(key string) : time.Duration
- IsSet(key string) : bool
- AllSettings() : map[string]interface{}
通過傳入.分隔的路徑
// Viper可以通過傳入.分隔的路徑來訪問嵌套字段: mysqlHost := viper.GetString("mysql.host") // 訪問mysql的host字段 fmt.Println("Mysql Host:", mysqlHost) mysqlPort := viper.GetInt("mysql.port") // 訪問mysql的port字段 fmt.Println("Mysql Port:", mysqlPort)
提取子樹
// 提取子樹 appConfig := viper.Sub("app") // 提取app子樹 fmt.Println("App Config:", appConfig.AllSettings()) // 打印app子樹的所有設置 cache1 := appConfig.GetStringMapString("cache1") // 提取app子樹的cache1字段 cache2 := viper.Sub("app.cache2") // 提取app子樹的cache2字段 fmt.Println("Cache1:", cache1) // 打印app子樹的cache字段 fmt.Println("Cache2:", cache2.AllSettings()) // 打印app子樹的cache2字段的所有設置
反序列化
// 反序列化 var conf Config err = viper.Unmarshal(&conf) // 反序列化到結(jié)構(gòu)體 if err != nil { panic(fmt.Errorf("unable to decode into struct, %v", err)) // 處理錯誤 } fmt.Println("Config Struct:", conf) // 打印反序列化后的結(jié)構(gòu)體
到此這篇關于go配置管理框架viper的文章就介紹到這了,更多相關go配置管理viper內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
golang并發(fā)編程使用Select語句的實現(xiàn)
Go語言中的select語句是并發(fā)編程中的重要工具,允許Goroutine等待多個通道操作,它阻塞直至任一case可執(zhí)行,可用于接收數(shù)據(jù)、實現(xiàn)超時機制和非阻塞通道操作,感興趣的可以了解一下2024-10-10