注:本文為博主,首次接觸項目時的入門級配置實操
在 Go 后端中,使用配置文件管理參數(如數據庫連接、服務端口等)是必備技能。Viper 是 Go 生態中最流行的配置管理庫。支持多種配置文件、環境變量、命令行參數等,并具備熱更新能力。
(熱更新:無需重新啟動應用,適用于小范圍、高頻更新)
第一目:首先安裝viper
go get github.com/spf13/viper
第二目:基礎使用步驟(附代碼)
1、創建配置文件
# config.yaml
server:host: "localhost"port: 8081
database:user: "admin"password: "secret"max_connections: 100
2、初始化 Viper 并讀取配置
package configimport ("github.com/fsnotify/fsnotify""github.com/spf13/viper"
)func Init() error {viper.SetConfigName("config") // 配置文件名(不含擴展名)viper.SetConfigType("yaml") // 文件類型viper.AddConfigPath("config") // 搜索路徑(當前目錄)// 讀取配置if err := viper.ReadInConfig(); err != nil {return err}// 監聽配置變更viper.WatchConfig()viper.OnConfigChange(func(e fsnotify.Event) {println("配置已更新!新端口:", viper.GetInt("server.port"))})return nil
}
3、在代碼中獲取配置
package mainimport ("fmt""github.com/renhongcai/gomodule/config""github.com/spf13/viper"
)func main() {if err := config.Init(); err != nil {panic("配置初始化失敗:" + err.Error())}host := viper.GetString("server.host") // 讀取配置port := viper.GetInt("server.port") // 設置端口號fmt.Printf("服務啟動于:%s:%d\n", host, port)}
4、viper支持的熱更新
滯塞一下程序,然后手動更改端口:
package mainimport ("fmt""github.com/renhongcai/gomodule/config""github.com/spf13/viper"
)func main() {if err := config.Init(); err != nil {panic("配置初始化失敗:" + err.Error())}host := viper.GetString("server.host") // 讀取配置port := viper.GetInt("server.port") // 設置端口號for true {// 手動阻塞}fmt.Printf("服務啟動于:%s:%d\n", host, port)}
更改端口號config.yaml中的 port 8081?-> 8082
打印效果:
配置已更新!新端口: 8082
第三目:進階的一些操作
1、設置默認值
// 默認
viper.SetDefault("server.port", 3000) // 默認端口,防崩潰
2、綁定環境變量
// 自動調用
viper.AutomaticEnv() // 自動讀取環境變量
viper.BindEnv("server.port", "APP_PORT") // 綁定 APP_PORT 到 server.port
3、映射到結構體(更推薦)
這樣更安全,更省心
type ServerConfig struct {Host string `mapstructure:"host"`Port int `mapstructure:"port"`
}
main中?
func Init(){var serverCfg ServerConfigviper.UnmarshalKey("server", &serverCfg) // 將 server 節點映射到結構體
}
4、多文件支持
viper.SetConfigFile("db.yaml")
viper.MergeInConfig() // 合并到已有配置
第四目:本篇博客的結構
.
├── config
│ ├── config.go # Viper 初始化代碼
│ └── config.yaml # 主配置文件
├── main.go # 程序入口
└── go.mod
第五目:經驗總結
路徑!!路徑!!路徑!!非常容易配置錯
若是大型項目的話,可以將配置文件按照功能,拆分成多個yaml(redis.yaml、http.yaml)
最終通過咱們上方的那個多文件支持,根據需求進行合并操作....
(注:注意其優先級順序:命令好參數 > 環境變量 > 配置文件 > 默認值)