Skip to content

系统设置模块 ​

设置模块(settings)提供全局和租户级键值配置管理。支持敏感数据自动脱敏、全局配置向租户配置的回退继承。

架构概览 ​

modules/settings/
├── domain/          # Setting 实体、DTO、Repository 接口
├── application/     # Service(全局/租户配置读写)
├── infrastructure/  # GORM SettingRepository 实现、AutoMigrate
└── interfaces/      # HTTP Handler、路由注册

数据模型 ​

Setting 实体 ​

字段类型说明
IDuint主键
TenantIDstring(36)租户 ID,空字符串表示全局配置
Keystring(128)配置键名
Valuetext配置值
Typestring(16)值类型,默认 string
Scopestring(16)作用域:global 或 tenant
UpdatedByuint最后更新用户 ID

数据库表: settings

索引: 复合唯一索引 idx_tenant_key — (TenantID, Key)

配置层级 ​

全局配置(TenantID = "")
    ↓ 回退
租户配置(TenantID = "uuid-xxx")

读取租户配置时,如果该 Key 在租户级别不存在,自动回退到全局配置。

API 接口 ​

所有接口需认证 + 多租户中间件。

全局配置 ​

方法路径权限说明
GET/api/v1/settingssettings.read全局配置列表
GET/api/v1/settings/global/:keysettings.read获取全局配置
PUT/api/v1/settings/global/:keysettings.write更新全局配置

租户配置 ​

方法路径权限说明
GET/api/v1/settings/tenantsettings.read租户配置列表
GET/api/v1/settings/tenant/:keysettings.read获取租户配置(回退全局)
PUT/api/v1/settings/tenant/:keysettings.write更新租户配置
DELETE/api/v1/settings/tenant/:keysettings.write删除租户配置

敏感数据脱敏 ​

当配置 Key 匹配以下敏感模式时,API 响应中的 Value 字段自动脱敏:

敏感模式: secret、password、passwd、token、api_key、apikey、access_key、private_key、credential、auth

脱敏规则:

  • 值长度 ≤ 8:返回 ********
  • 值长度 > 8:返回 前4位****后4位

响应 DTO 中 masked: true 标识该值已脱敏。

请求/响应示例 ​

更新配置 ​

json
// PUT /api/v1/settings/tenant/site_name
// Request
{
  "value": "MengStack Demo",
  "type": "string"
}

// Response 200 OK

获取敏感配置(脱敏) ​

json
// GET /api/v1/settings/tenant/api_secret_key
// Response 200
{
  "id": 5,
  "tenant_id": "uuid-xxx",
  "key": "api_secret_key",
  "value": "abcd****wxyz",
  "type": "string",
  "scope": "tenant",
  "updated_by": 1,
  "updated_at": "2026-10-01T10:00:00Z",
  "masked": true
}

存储实现 ​

Repository 使用 find-then-create-or-update 模式实现 Upsert:

  1. 按 (tenant_id, key) 查询
  2. 不存在 → 创建新记录
  3. 已存在 → 更新 value、type、updated_by

依赖注入 ​

go
fx.Module("settings",
    fx.Provide(
        infrastructure.NewSettingRepository,
        application.NewService,
        NewHandler,
    ),
)

Released under the Apache 2.0 License.