2023-12-15 18:08:06 +08:00
|
|
|
|
package config
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"flag"
|
|
|
|
|
"fmt"
|
|
|
|
|
"log/slog"
|
|
|
|
|
|
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type Config struct {
|
|
|
|
|
Mqtt mqtt
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// MQTT客户端配置
|
|
|
|
|
type mqtt struct {
|
|
|
|
|
Topic topic
|
|
|
|
|
ClientId string
|
|
|
|
|
Address string
|
|
|
|
|
Username string
|
|
|
|
|
Password string
|
|
|
|
|
KeepAlive uint16 // 保活时间间隔,单位s
|
|
|
|
|
ConnectRetryDelay uint16 // 连接重试延时,单位s
|
|
|
|
|
ConnectTimeout uint16 // 连接操作超时,单位s
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type topic struct {
|
|
|
|
|
App string
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var Cfg Config
|
|
|
|
|
|
|
|
|
|
// 获取配置文件名称,从运行flag参数config中获取,若未提供,使用默认'dev'
|
|
|
|
|
func getConfigName() string {
|
|
|
|
|
configName := ""
|
|
|
|
|
flag.StringVar(&configName, "config", "dev", "config name, eg: -config test")
|
|
|
|
|
flag.Parse()
|
|
|
|
|
if configName == "" {
|
|
|
|
|
configName = "dev"
|
|
|
|
|
}
|
|
|
|
|
slog.Info("读取配置文件", "配置文件名称", configName)
|
|
|
|
|
return configName
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 加载配置
|
|
|
|
|
func LoadConfig() {
|
|
|
|
|
cnf := viper.New()
|
|
|
|
|
cnf.SetConfigName(getConfigName())
|
|
|
|
|
cnf.SetConfigType("yml")
|
|
|
|
|
cnf.AddConfigPath("./config/")
|
|
|
|
|
cnf.AddConfigPath(".")
|
2023-12-19 16:15:21 +08:00
|
|
|
|
cnf.AddConfigPath("../config/")
|
2023-12-15 18:08:06 +08:00
|
|
|
|
err := cnf.ReadInConfig()
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic(fmt.Errorf("读取配置文件错误: %w", err))
|
|
|
|
|
}
|
|
|
|
|
err = cnf.Unmarshal(&Cfg)
|
|
|
|
|
if err != nil {
|
|
|
|
|
panic(fmt.Errorf("解析配置文件错误: %w", err))
|
|
|
|
|
}
|
|
|
|
|
slog.Info("成功加载配置", "config", Cfg)
|
|
|
|
|
}
|