goweb3系列解析3 :goconfig 配置解析模块分析
goconfig 配置解析模块分析一、整体架构goconfig是 goweb3 项目的核心配置管理模块基于Viper构建提供多环境配置、环境变量替换、敏感信息加密解密等能力。┌─────────────────────────────────────────────────────────────┐ │ goconfig 模块架构 │ ├─────────────────────────────────────────────────────────────┤ │ 配置文件层 │ │ ├── env.yml # 环境标识配置 │ │ ├── ichub-{env}.yml # 各环境主配置文件 │ │ └── base/common-{env}.yml # 公共配置文件 │ ├─────────────────────────────────────────────────────────────┤ │ 核心解析层 │ │ ├── IchubConfig # 统一配置结构体 │ │ ├── ConfigItem # 配置项解析器环境变量加密 │ │ └── Viper # 底层配置解析引擎 │ ├─────────────────────────────────────────────────────────────┤ │ 数据源适配层 │ │ ├── MySQL/Postgres/Clickhouse 数据库配置 │ │ ├── Redis/NATS/ES 中间件配置 │ │ ├── Web/RPC 服务配置 │ │ └── Etcd 服务发现配置 │ └─────────────────────────────────────────────────────────────┘二、核心组件详解1. IchubConfig - 统一配置结构体gotype IchubConfig struct { viper *viper.Viper // Viper 实例 Env string // 当前环境标识 UseCommon string // 是否使用公共配置 // 数据源配置 Datasource struct { ... } // 默认数据源 Mysql struct { ... } // MySQL 配置 Postgres *DbClientDto // PostgreSQL 配置 Clickhouse struct { ... } // ClickHouse 配置 Redis struct { ... } // Redis 配置 // 中间件配置 Es struct { ... } // Elasticsearch Nats NatsClientDto // NATS 消息队列 // 服务配置 Web struct { ... } // Web 服务 Rpc struct { ... } // RPC 服务 Etcd struct { ... } // Etcd 服务发现 // 框架配置 Gorm GormClientDto // GORM 配置 Factroy FactroyClientDto // 工厂模式配置 }2. 配置文件加载流程gofunc (self *IchubConfig) ReadConfig(basePath string) error { // 1. 设置默认基础路径 self.SetDefaultBasePath(basePath) // 2. 读取环境配置 env.yml self.ReadConfigEnv() // 3. 如果启用公共配置先加载 common 配置 if self.IfUseCommon() { var cfg, err self.ReadCommonConfig() self.From(cfg) // 合并公共配置 } // 4. 加载对应环境的主配置文件 // 文件路径: {basePath}/config/ichub-{env}.yml viper.ReadInConfig() viper.Unmarshal(self) // 5. 解析配置项环境变量替换、解密 self.Parse() }三、配置项解析机制1. 环境变量替换配置文件支持${ENV_VAR:default}格式的环境变量替换yaml# env.yml Env: ${ICHUB_ENV:postgres}解析逻辑 (config_item.go):go// ${HOSTURL:huawei.akunlong.top:2379} func (this *ConfigItem) parseEndValue() *ConfigItem { // 提取环境变量名和默认值 this.EnvValue ICHUB_ENV // 环境变量名 this.DefaultValue postgres // 默认值 // 优先使用环境变量否则使用默认值 if os.Getenv(this.EnvValue) ! { this.EndValue os.Getenv(this.EnvValue) } else { this.EndValue this.DefaultValue } return this }2. 敏感信息加密支持 AES 加密的敏感信息格式为enc(加密内容)gofunc (this *ConfigItem) Decrypt() string { if strings.Contains(this.EndValue, enc() { // 提取加密内容: enc(xxx) - xxx eval strings.Trim(eval, enc() eval strings.Trim(eval, )) // AES 解密 eval encrypt.AesDecBase64(eval) this.EndValue eval } return this.EndValue }四、多环境配置管理1. 环境标识环境标识说明开发环境dev本地开发测试环境test测试验证生产环境master/prod线上生产发布环境release预发布2. 配置文件命名约定plainTextconfig/ ├── env.yml # 环境标识 ├── ichub-dev.yml # 开发环境配置 ├── ichub-test.yml # 测试环境配置 ├── ichub-master.yml # 生产环境配置 ├── ichub-release.yml # 发布环境配置 └── base/ ├── common-dev.yml # 公共配置(开发) ├── common-test.yml # 公共配置(测试) └── common-master.yml # 公共配置(生产)3. 环境判断方法gofunc IfMaster() bool { return FindBeanIchubConfig().FindEnv() master || FindBeanIchubConfig().FindEnv() prod } func IfDev() bool { return FindBeanIchubConfig().FindEnv() dev } func IfTest() bool { return FindBeanIchubConfig().FindEnv() test }五、依赖注入与单例模式1. 自动注册gofunc init() { registerBeanIchubConfig() } func registerBeanIchubConfig() { _ basedi.RegisterLoadBean(singleNameIchubConfig, LoadIchubConfig) }2. 获取配置实例gofunc FindBeanIchubConfig() *IchubConfig { return basedi.FindBean(singleNameIchubConfig).(*IchubConfig) }六、配置读取方法1. 通用读取方法方法功能ReadString(pathkey)读取字符串配置ReadInt(pathkey)读取整数配置ReadMap(pathkey)读取 Map 配置ReadStruct(pathkey, obj)读取并映射到结构体2. 数据源读取方法go// 根据配置的 dbType 自动选择数据源 func (self *IchubConfig) ReadIchubDb() *DbClientDto { switch self.Gorm.DbType { case mysql: return self.ReadIchubMysql() case postgres: return self.ReadIchubDatasource() case clickhouse: return self.ReadIchubClickhouse() } }3. 服务配置读取方法方法返回类型说明ReadIchubWebServer()WebServerDtoWeb 服务配置ReadIchubRpc()RpcServerDtoRPC 服务配置ReadIchubEs()ElasticClientDtoES 客户端配置ReadIchubRedis()RedisClientDtoRedis 配置ReadNats()NatsClientDtoNATS 配置七、配置文件示例env.yml - 环境标识yamlEnv: ${ICHUB_ENV:postgres} # 环境变量优先默认 postgres UseCommon: false # 是否使用公共配置ichub-dev.yml - 开发环境配置yamlsoftware: env: dev webPrefix: /api web: server: name: web-server ip: 0.0.0.0 port: 8080 ver: v1.0 datasource: dbtype: mysql dbname: example_db host: localhost port: 3306 username: ${DB_USER:root} password: ${DB_PASS:root} redis: db: 0 addr: localhost:6379 password: 八、设计亮点特性实现方式优势单例模式依赖注入 懒加载避免重复解析保证配置一致性多环境支持环境变量 文件命名约定灵活切换环境配置隔离环境变量替换${ENV:default}语法支持容器化部署敏感信息外置敏感信息加密AES Base64配置文件安全存储公共配置合并UseCommon 开关配置复用减少重复类型安全结构体映射编译时检查避免运行时错误九、使用示例go// 获取配置实例 cfg : ichubconfig.FindBeanIchubConfig() // 读取基础配置 env : cfg.ReadEnv() // 获取当前环境 basePath : cfg.GetBathPath() // 获取基础路径 // 读取数据库配置 dbConfig : cfg.ReadIchubDb() dbHost : dbConfig.Host dbPort : dbConfig.Port // 读取 Web 服务配置 webServer : cfg.ReadIchubWebServer() serverPort : webServer.ServerPort // 读取 Redis 配置 redisConfig : cfg.ReadIchubRedis() redisAddr : redisConfig.Addr // 动态读取配置项 apiKey : cfg.ReadString(web.server.api_key) timeout : cfg.ReadInt(web.client.web_timeout)十、配置解析流程总结plainTextgoconfig是goweb3项目的核心配置管理模块基于Viper构建支持多环境配置管理。主要特性包括 架构分层清晰包含配置文件层env.yml环境配置、核心解析层统一结构体Viper引擎和数据源适配层 支持多环境dev/test/master等配置隔离通过文件命名约定实现 提供环境变量替换${ENV_VAR:default}格式和AES加密敏感信息功能 采用单例模式依赖注入保证配置一致性避免重复解析 支持公共配置合并通过UseCommon开关控制 提供类型安全的配置读取启动应用 ↓ 注册 IchubConfig 单例 (init) ↓ 调用 FindBeanIchubConfig() ↓ ReadConfig() 加载配置 ├── 读取 env.yml 确定环境 ├── 加载 common-{env}.yml (可选) ├── 加载 ichub-{env}.yml └── 解析配置项环境变量替换、解密 ↓ 返回配置实例供业务使用