Documentation
¶
Index ¶
- Constants
- Variables
- func GetBool(key string) bool
- func GetInt(key string) int
- func GetString(key string) string
- func GetStringMap(key string) map[string]any
- func GetViper() *viper.Viper
- func RegisterCallback(cb func(*Config))
- func RegisterDSNBuilder(name string, builder DSNBuilder, aliases ...string)
- func RegisteredDrivers() []string
- func Reload() error
- func Set(cfg *Config)
- func SetDefaultManager(m *Manager)
- func StartWatcher() error
- func StopWatcher()
- type AppConfig
- type CORSConfig
- type Config
- type DSNBuilder
- type DatabaseConfig
- type JWTConfig
- type LocalStorageConfig
- type LogConfig
- type Manager
- func (m *Manager) Get() *Config
- func (m *Manager) GetViper() *viper.Viper
- func (m *Manager) Load() (*Config, error)
- func (m *Manager) LoadWithWatch(onChange func(*Config)) (*Config, error)
- func (m *Manager) RegisterCallback(cb func(*Config))
- func (m *Manager) Reload() error
- func (m *Manager) Set(cfg *Config)
- func (m *Manager) StartWatcher() error
- func (m *Manager) StopWatcher()
- type OSSStorageConfig
- type RedisConfig
- type SMSConfig
- type ServerConfig
- type StorageConfig
- type TLSConfig
- type UploadConfig
- type UploadPolicy
Constants ¶
const ( DriverMySQL = "mysql" DriverPostgres = "postgres" )
数据库驱动常量
Variables ¶
var (
ErrConfigNotLoaded = fmt.Errorf("配置未加载")
)
配置错误
Functions ¶
func RegisterDSNBuilder ¶
func RegisterDSNBuilder(name string, builder DSNBuilder, aliases ...string)
RegisterDSNBuilder 为指定驱动注册 DSN 构建器(驱动名大小写不敏感)。 aliases 用于注册同一驱动的别名,例如 postgres 的 "postgresql"、"pg"。 通常由 database 包通过 database.RegisterDialect 间接调用, 应用代码也可直接使用以扩展自定义驱动。
func RegisteredDrivers ¶
func RegisteredDrivers() []string
RegisteredDrivers 返回所有已注册 DSN 构建器的驱动名(用于诊断)
func SetDefaultManager ¶
func SetDefaultManager(m *Manager)
SetDefaultManager 替换全局默认配置管理器。 主要供应用层(如 App)在持有自己的 Manager 时使用, 使 config.Get / config.GetString 等便捷函数仍然能取到正确的配置。 传入 nil 表示重置为空管理器。
C10a:经 atomic.Pointer.Store 原子置换,消除与并发读取(Get 等)的数据竞争。
Types ¶
type AppConfig ¶
type AppConfig struct {
Name string `mapstructure:"name"` // 应用名称,如 "用户管理系统"
SiteName string `mapstructure:"site_name"` // 站点别名,如 "site_a"、"user_api"
Version string `mapstructure:"version"` // 应用版本
Env string `mapstructure:"env"` // 运行环境: dev/test/prod
Debug bool `mapstructure:"debug"` // 是否开启调试模式
BaseURL string `mapstructure:"base_url"` // 应用基础URL
}
AppConfig 应用配置 使用场景:
- 缓存键名前缀: cache:{site_name}:user:1
- 日志标识: [site_a] 2024-01-01 10:00:00 ...
- 站点追踪: Request-ID 带站点标识
- 分布式锁: lock:{site_name}:order:123
func (*AppConfig) GetCachePrefix ¶
GetCachePrefix 获取缓存键名前缀
func (*AppConfig) GetSiteName ¶
GetSiteName 获取站点别名,如果未设置则返回空字符串
type CORSConfig ¶
type CORSConfig struct {
AllowedOrigins []string `mapstructure:"allowed_origins"` // 允许的域名列表
AllowedMethods []string `mapstructure:"allowed_methods"` // 允许的方法
AllowedHeaders []string `mapstructure:"allowed_headers"` // 允许的请求头
ExposedHeaders []string `mapstructure:"exposed_headers"` // 暴露的响应头
AllowCredentials bool `mapstructure:"allow_credentials"` // 是否允许携带凭证
MaxAge int `mapstructure:"max_age"` // 预检请求缓存时间(秒)
}
CORSConfig CORS 跨域配置
func (*CORSConfig) GetAllowedHeaders ¶
func (c *CORSConfig) GetAllowedHeaders() []string
GetAllowedHeaders 获取允许的请求头列表
func (*CORSConfig) GetAllowedMethods ¶
func (c *CORSConfig) GetAllowedMethods() []string
GetAllowedMethods 获取允许的方法列表
func (*CORSConfig) GetAllowedOrigins ¶
func (c *CORSConfig) GetAllowedOrigins() []string
GetAllowedOrigins 获取允许的域名列表
func (*CORSConfig) GetExposedHeaders ¶
func (c *CORSConfig) GetExposedHeaders() []string
GetExposedHeaders 获取暴露的响应头列表
type Config ¶
type Config struct {
App AppConfig `mapstructure:"app"`
Server ServerConfig `mapstructure:"server"`
Database DatabaseConfig `mapstructure:"database"`
Redis RedisConfig `mapstructure:"redis"`
JWT JWTConfig `mapstructure:"jwt"`
SMS SMSConfig `mapstructure:"sms"`
Storage StorageConfig `mapstructure:"storage"`
Upload UploadConfig `mapstructure:"upload"`
Log LogConfig `mapstructure:"log"`
CORS CORSConfig `mapstructure:"cors"`
}
Config 全局配置结构体
func Load ¶
Load 加载配置文件(C3.5 修复:替换前停止旧 Manager 的 watcher,防止 goroutine 泄漏)。 P1 #8:全程持 pkgLoadMu 串行化,消除与并发 Load/LoadWithWatch 的 TOCTOU。
func LoadWithWatch ¶
LoadWithWatch 加载配置文件并启用热更新(C3.5 修复:替换前停止旧 watcher)。 P1 #8:全程持 pkgLoadMu 串行化,且新 manager 在其 watcher 成功启动后才置换为默认; 启动失败则停掉半启动的 watcher 并不置换,避免遗留孤儿 watcher。
func (*Config) Clone ¶ added in v1.2.0
Clone 返回 Config 的深拷贝(M-G 修复)。
标量字段与子结构体经结构体值拷贝独立;所有切片字段(CORS 的 4 个列表、Upload 的 2 个 类型白名单、Storage.Local/OSS 上传策略的扩展名/MIME 白名单)深拷贝底层数组,使返回值 可被调用方安全修改(含 append/sort/改元素)而不污染框架内部配置、不与其他读者竞态。
用于需要可变配置副本的场景。热路径的 Get() 为零分配仍返回内部只读指针——需要改配置时 用 Clone() 或 Load()(Load 内部已返回 Clone)。
type DSNBuilder ¶
type DSNBuilder func(*DatabaseConfig) string
DSNBuilder 根据 DatabaseConfig 生成连接字符串
func LookupDSNBuilder ¶
func LookupDSNBuilder(name string) (DSNBuilder, bool)
LookupDSNBuilder 查找已注册的 DSN 构建器
type DatabaseConfig ¶
type DatabaseConfig struct {
// Driver 数据库驱动,支持 mysql(默认)与 postgres
Driver string `mapstructure:"driver"`
// Host 数据库主机
Host string `mapstructure:"host"`
// Port 数据库端口
Port int `mapstructure:"port"`
// User 数据库用户名
User string `mapstructure:"user"`
// Password 数据库密码
Password string `mapstructure:"password"`
// Name 数据库名
Name string `mapstructure:"name"`
// Timezone 连接时区。MySQL 用作 loc 参数、Postgres 用作 TimeZone 参数。
// 空时 MySQL 默认 "Local"、Postgres 默认 "Asia/Shanghai"(向后兼容,M9)。
Timezone string `mapstructure:"timezone"`
// CustomDSN 自定义连接字符串,设置后优先于由 Host/Port 等字段生成的 DSN
CustomDSN string `mapstructure:"dsn"`
// MaxIdleConns 最大空闲连接数
MaxIdleConns int `mapstructure:"max_idle_conns"`
// MaxOpenConns 最大打开连接数
MaxOpenConns int `mapstructure:"max_open_conns"`
// ConnMaxIdleTime 连接最大空闲时间,如 "5m"(#21)。0 表示用驱动默认
ConnMaxIdleTime time.Duration `mapstructure:"conn_max_idle_time"`
// HealthCheckInterval 主库探活间隔,如 "30s"(#21)。0 表示用默认 30s
HealthCheckInterval time.Duration `mapstructure:"health_check_interval"`
// HealthCheckFailureThreshold 连续探活失败多少次标记不健康(#21)。0 表示用默认 3
HealthCheckFailureThreshold int `mapstructure:"health_check_failure_threshold"`
}
DatabaseConfig 数据库配置
func (*DatabaseConfig) DSN ¶
func (c *DatabaseConfig) DSN() string
DSN 根据驱动返回连接字符串。设置了 CustomDSN 时优先返回 CustomDSN; 未指定 Driver 时按 MySQL 处理(向后兼容)。 若驱动通过 RegisterDSNBuilder 注册过自定义构建器,则使用注册的构建器。
func (*DatabaseConfig) MySQLDSN ¶
func (c *DatabaseConfig) MySQLDSN() string
MySQLDSN 返回 MySQL 连接字符串。 密码经 url.QueryEscape 转义,避免含 @/:/空格 等特殊字符破坏 DSN(M9)。 loc 由 Timezone 配置,空则默认 "Local"(向后兼容)。
func (*DatabaseConfig) PostgresDSN ¶
func (c *DatabaseConfig) PostgresDSN() string
PostgresDSN 返回 PostgreSQL 连接字符串。 密码经单引号转义(内嵌单引号翻倍),避免含空格/引号/反斜杠破坏 key=value DSN(M9)。 TimeZone 由 Timezone 配置,空则默认 "Asia/Shanghai"(向后兼容)。
type JWTConfig ¶
type JWTConfig struct {
Secret string `mapstructure:"secret"`
Expire time.Duration `mapstructure:"expire"` // 过期时间,如 "24h"(time.Duration)
RefreshExpire time.Duration `mapstructure:"refresh_expire"` // 刷新 token 过期时间,如 "168h"
Issuer string `mapstructure:"issuer"` // 签发者
Algorithm string `mapstructure:"algorithm"` // 签名算法:HS256(默认)/HS384/HS512;非 HMAC 算法(如 RS256)会被 jwt.signingMethod 拒绝(ErrUnsupportedAlgorithm)
}
JWTConfig JWT 配置
type LocalStorageConfig ¶
type LocalStorageConfig struct {
Path string `mapstructure:"path"`
BaseURL string `mapstructure:"base_url"`
// Upload 上传安全策略(可选,零值不限制)。
Upload UploadPolicy `mapstructure:"upload"`
// MaxReadBytes Get 读取单文件上限(字节)。0 = 默认 100MB,-1 = 不限制。
MaxReadBytes int64 `mapstructure:"max_read_bytes"`
}
LocalStorageConfig 本地存储配置
type LogConfig ¶
type LogConfig struct {
Dir string `mapstructure:"dir"`
MaxSize int `mapstructure:"max_size"` // MB
MaxBackups int `mapstructure:"max_backups"`
MaxAge int `mapstructure:"max_age"` // 天
Compress bool `mapstructure:"compress"`
}
LogConfig 日志配置
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager 配置管理器
func (*Manager) Get ¶
Get 获取配置。
返回的是 Manager 内部持有的配置指针(共享),调用方**必须视为只读**: 修改返回值的标量或切片元素会污染全局配置并与其他读取 goroutine 竞态。需要可变副本时 用 Clone()(返回深拷贝)或 Load()(重载并返回深拷贝)。
M-G:热路径(jwt 鉴权等每请求调用)保持返回内部指针以零分配,可变副本走 Clone()。 框架自身的 reload 创建新 Config 并替换 m.cfg 指针,不改写旧 Config 对象,故 Get() 返回的旧指针在 reload 后仍指向一致的(旧)快照,reload 不引入对旧快照的竞态。
func (*Manager) LoadWithWatch ¶
LoadWithWatch 加载配置文件并启用热更新
func (*Manager) RegisterCallback ¶
RegisterCallback 注册配置变更回调
func (*Manager) Reload ¶
Reload 重新加载配置文件。读取、解析、校验(C10b)任一步失败均保留旧配置并返回错误; 仅当新配置通过 Validate 后才替换 m.cfg 并触发回调。
func (*Manager) StartWatcher ¶
StartWatcher 启动配置文件监听。使用自管的 fsnotify.Watcher(监听配置文件 所在目录以兼容编辑器改写/k8s ConfigMap 原子替换),文件变更时去抖后重新加载。 幂等:重复调用不会创建多个监听 goroutine。
func (*Manager) StopWatcher ¶
func (m *Manager) StopWatcher()
StopWatcher 停止配置文件监听并释放 watcher(C10d)。幂等。 关闭 fsnotify watcher → Events 通道关闭 → watchLoop 退出 → 等待 watchDone。
type OSSStorageConfig ¶
type OSSStorageConfig struct {
Endpoint string `mapstructure:"endpoint"`
Bucket string `mapstructure:"bucket"`
AccessKeyID string `mapstructure:"access_key_id"`
AccessKeySecret string `mapstructure:"access_key_secret"`
BaseURL string `mapstructure:"base_url"`
// Upload 上传安全策略(可选,零值不限制)。
Upload UploadPolicy `mapstructure:"upload"`
// MaxReadBytes Get 读取单文件上限(字节)。0 = 默认 100MB,-1 = 不限制。
MaxReadBytes int64 `mapstructure:"max_read_bytes"`
}
OSSStorageConfig OSS 存储配置
type RedisConfig ¶
type RedisConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
Password string `mapstructure:"password"`
DB int `mapstructure:"db"`
}
RedisConfig Redis 配置
type SMSConfig ¶
type SMSConfig struct {
Enabled bool `mapstructure:"enabled"`
Provider string `mapstructure:"provider"`
AccessKeyID string `mapstructure:"access_key_id"`
AccessKeySecret string `mapstructure:"access_key_secret"`
SignName string `mapstructure:"sign_name"`
TemplateCode string `mapstructure:"template_code"`
}
SMSConfig 短信配置
type ServerConfig ¶
type ServerConfig struct {
Host string `mapstructure:"host"` // 绑定地址,空=监听所有接口(0.0.0.0);"127.0.0.1"=仅本机;内网IP=绑定指定网卡
Port int `mapstructure:"port"`
Mode string `mapstructure:"mode"` // development 或 production
ReadTimeout time.Duration `mapstructure:"read_timeout"` // 读超时,如 "15s"
WriteTimeout time.Duration `mapstructure:"write_timeout"` // 写超时,如 "30s"
IdleTimeout time.Duration `mapstructure:"idle_timeout"` // 空闲超时,如 "60s"
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout"` // 优雅关闭超时,如 "30s"
MaxHeaderBytes int `mapstructure:"max_header_bytes"` // 最大请求头字节数
TLS TLSConfig `mapstructure:"tls"`
UnixSocket string `mapstructure:"unix_socket"` // 非空时优先于 Port,监听 unix socket
ResponseMode string `mapstructure:"response_mode"` // business(默认) 或 rest,见 response.SetMode
}
ServerConfig 服务配置
func (ServerConfig) EffectiveIdleTimeout ¶ added in v1.1.0
func (c ServerConfig) EffectiveIdleTimeout() time.Duration
EffectiveIdleTimeout 返回生效的空闲超时(零值回退默认)
func (ServerConfig) EffectiveMaxHeaderBytes ¶ added in v1.1.0
func (c ServerConfig) EffectiveMaxHeaderBytes() int
EffectiveMaxHeaderBytes 返回生效的最大请求头字节数(零值回退默认)
func (ServerConfig) EffectiveReadTimeout ¶ added in v1.1.0
func (c ServerConfig) EffectiveReadTimeout() time.Duration
EffectiveReadTimeout 返回生效的读超时(零值回退默认)
func (ServerConfig) EffectiveShutdownTimeout ¶ added in v1.1.0
func (c ServerConfig) EffectiveShutdownTimeout() time.Duration
EffectiveShutdownTimeout 返回生效的关闭超时(零值回退默认)
func (ServerConfig) EffectiveWriteTimeout ¶ added in v1.1.0
func (c ServerConfig) EffectiveWriteTimeout() time.Duration
EffectiveWriteTimeout 返回生效的写超时(零值回退默认)
type StorageConfig ¶
type StorageConfig struct {
Driver string `mapstructure:"driver"` // local 或 oss
Local LocalStorageConfig `mapstructure:"local"`
OSS OSSStorageConfig `mapstructure:"oss"`
}
StorageConfig 文件存储配置
type TLSConfig ¶ added in v1.1.0
type TLSConfig struct {
Enabled bool `mapstructure:"enabled"`
CertFile string `mapstructure:"cert_file"`
KeyFile string `mapstructure:"key_file"`
}
TLSConfig HTTPS/TLS 配置
type UploadConfig ¶
type UploadConfig struct {
MaxFileSize int `mapstructure:"max_file_size"` // 最大图片大小(MB)
MaxVideoSize int `mapstructure:"max_video_size"` // 最大视频大小(MB)
MaxAvatarSize int `mapstructure:"max_avatar_size"` // 最大头像大小(MB)
AllowedImageTypes []string `mapstructure:"allowed_image_types"` // 允许的图片 MIME 类型
AllowedVideoTypes []string `mapstructure:"allowed_video_types"` // 允许的视频 MIME 类型
}
UploadConfig 上传配置
type UploadPolicy ¶ added in v1.2.0
type UploadPolicy struct {
// MaxSizeBytes 单文件大小上限(字节)。0 = 不限制。
MaxSizeBytes int64 `mapstructure:"max_size_bytes"`
// AllowedExts 允许的扩展名白名单(小写、含点,如 ".jpg")。空 = 不限制。
AllowedExts []string `mapstructure:"allowed_exts"`
// AllowedMIMEs 允许的 MIME 类型白名单(小写,如 "image/jpeg")。
// 非空时用 http.DetectContentType 嗅探文件前 512 字节校验。空 = 不嗅探。
AllowedMIMEs []string `mapstructure:"allowed_mime_types"`
}
UploadPolicy 上传安全策略(C4b)。零值表示不限制,向后兼容; 生产环境强烈建议显式配置 MaxSizeBytes 与 AllowedExts / AllowedMIMEs。