// subconfigs/service_config.go package subconfigs import ( "fmt" "log" ) // ServiceConfig 数据库配置 type ServiceConfig struct { BaseConfig AppName string `yaml:"app_name"` //当前应用名称 AppVersion string `yaml:"app_version"` //当前应用版本 AppEnv string `yaml:"app_env"` //环境参数 dev test prod AppAuthToken string `yaml:"app_auth_token"` //使用静态认证的时候使用的token Port int `yaml:"port"` ServiceName string `yaml:"service_name"` InstanceName string `yaml:"instance_name"` ReadTimeout int `yaml:"read_timeout"` WriteTimeout int `yaml:"write_timeout"` IdleTimeout int `yaml:"idle_timeout"` } // SetDefaults 设置默认值 - 实现 ConfigLoader 接口 func (c *ServiceConfig) SetDefaults() { if c.AppEnv == "" { c.AppEnv = "dev" } if c.Port == 0 { c.Port = 8080 } if c.IdleTimeout == 0 { c.IdleTimeout = 60 } if c.ReadTimeout == 0 { c.ReadTimeout = 30 } if c.WriteTimeout == 0 { c.WriteTimeout = 30 } } // Load 从yaml数据加载 - 实现 ConfigLoader 接口 func (c *ServiceConfig) Load(data map[string]interface{}) error { // 虽然可能不会被直接调用,但为了接口完整性还是要实现 return c.LoadFromYAML(data, c) } // ========== 业务方法 ========== // Validate 验证配置(数据库配置) func (c *ServiceConfig) Validate() error { if c.Port <= 0 || c.Port > 65535 { return fmt.Errorf("invalid service port: %d", c.Port) } return nil } // IsConfigured 判断是否已配置(数据库配置) func (c *ServiceConfig) IsConfigured() bool { if c.Port <= 0 { log.Println("⚠️ 警告: 微服务 Port 未配置或无效") return false } return true } // 自动注册 func init() { Register("service", &ServiceConfig{}) }