jl-iot/config/config.go
walker 5f94a5a146 mqtt客户端添加请求处理公共实现
基于请求处理实现Iot日志查询请求处理器注册接口
2023-12-19 16:15:21 +08:00

63 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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(".")
cnf.AddConfigPath("../config/")
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)
}