You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
2.0 KiB
66 lines
2.0 KiB
package config
|
|
|
|
import (
|
|
"github.com/google/uuid"
|
|
"github.com/spf13/viper"
|
|
"log"
|
|
"strings"
|
|
)
|
|
|
|
type Config struct {
|
|
Server ServerConfig `mapstructure:"server"`
|
|
Auth AuthConfig `mapstructure:"auth"`
|
|
Redis RedisConfig `mapstructure:"redis"`
|
|
}
|
|
type ServerConfig struct {
|
|
AppListenPort string `mapstructure:"app_listen_port"`
|
|
DeviceListenPort string `mapstructure:"device_listen_port"`
|
|
PublicAppAddr string `mapstructure:"public_app_addr"`
|
|
PublicDeviceAddr string `mapstructure:"public_device_addr"`
|
|
InstanceID string `mapstructure:"instance_id"`
|
|
}
|
|
type AuthConfig struct {
|
|
AppAccessSecret string `mapstructure:"app_access_secret"`
|
|
DeviceRelaySecret string `mapstructure:"device_relay_secret"`
|
|
}
|
|
|
|
type RedisConfig struct {
|
|
Enabled bool `mapstructure:"enabled"`
|
|
Addr string `mapstructure:"addr"`
|
|
Password string `mapstructure:"password"`
|
|
DB int `mapstructure:"db"`
|
|
|
|
// [新增]
|
|
InstanceRegistryKey string `mapstructure:"instance_registry_key"`
|
|
DeviceRelayMappingKey string `mapstructure:"device_relay_mapping_key"`
|
|
HeartbeatIntervalSeconds int `mapstructure:"heartbeat_interval_seconds"`
|
|
InstanceTTLSeconds int `mapstructure:"instance_ttl_seconds"`
|
|
}
|
|
|
|
var Cfg *Config
|
|
|
|
func LoadConfig() {
|
|
viper.SetConfigName("config")
|
|
viper.SetConfigType("yml")
|
|
viper.AddConfigPath(".")
|
|
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
|
viper.AutomaticEnv()
|
|
|
|
// 读取配置文件
|
|
if err := viper.ReadInConfig(); err != nil {
|
|
// 如果配置文件没找到,也没关系,可能完全通过环境变量配置
|
|
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
|
|
log.Fatalf("Fatal error reading config file: %v", err)
|
|
}
|
|
}
|
|
|
|
// 将读取到的配置反序列化到 Cfg 结构体中
|
|
if err := viper.Unmarshal(&Cfg); err != nil {
|
|
log.Fatalf("Unable to decode config into struct: %v", err)
|
|
}
|
|
|
|
if Cfg.Server.InstanceID == "" {
|
|
Cfg.Server.InstanceID = uuid.New().String()
|
|
}
|
|
log.Printf("Configuration loaded. Instance ID: %s", Cfg.Server.InstanceID)
|
|
}
|
|
|