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) error
- 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) GetBool(key string) bool
- func (m *Manager) GetInt(key string) int
- func (m *Manager) GetString(key string) string
- func (m *Manager) GetStringMap(key string) map[string]any
- 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) error
- func (m *Manager) StartWatcher() error
- func (m *Manager) StopWatcher()
- type OSSStorageConfig
- type RedisConfig
- type SMSConfig
- type ServerConfig
- type StorageConfig
- type TLSConfig
- type TraceConfig
- type UploadConfig
- type UploadPolicy
Constants ¶
const ( DriverMySQL = "mysql" DriverPostgres = "postgres" )
数据库驱动常量
const MySQLTLSConfigName = "xlgo-mysql"
MySQLTLSConfigName 是 database 包为 MySQL 私有 CA TLS 注册的命名配置名(M-config-2)。 当 DatabaseConfig.TLS=true 且 TLSRootCA 非空时,MySQLDSN 追加 tls=<本常量>, 由 database 包在 InitDB 时通过 go-sql-driver/mysql.RegisterTLSConfig 注册自定义 *tls.Config。 TLS=true 但 TLSRootCA 为空时则用内置 tls=true(系统根 CA),无需注册。
Variables ¶
var ( // L-config-4:无格式化的哨兵错误用 errors.New(fmt.Errorf 无动词等价但语义上后者暗示格式化)。 ErrConfigNotLoaded = errors.New("配置未加载") ErrInvalidConfig = errors.New("配置非法") )
配置错误
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 等)的数据竞争。 置换后会停止旧 Manager 的 watcher,避免全局默认 manager 切换后遗留热更新 goroutine。
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"`
Trace TraceConfig `mapstructure:"trace"`
}
Config 全局配置结构体
func Load ¶
Load 加载配置文件。 P1 #8:全程持 pkgLoadMu 串行化。新配置加载成功后才替换默认 Manager 并停止旧 watcher; 加载失败会保留旧 Manager 与旧 watcher,避免一次错误配置导致热更新链路断掉。
func LoadWithWatch ¶
LoadWithWatch 加载配置文件并启用热更新。 P1 #8:全程持 pkgLoadMu 串行化,且新 manager 在其 watcher 成功启动后才置换为默认; 启动失败则保留旧 Manager 与旧 watcher,并停掉新 manager 可能半启动的 watcher。
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"`
// SSLMode PostgreSQL sslmode(disable/allow/prefer/require/verify-ca/verify-full)。
// 空时默认 "prefer"(M-config-2:原硬编码 disable 已改为默认 prefer,优先加密、失败回退明文)。
// 该字段仅对 PostgreSQL 生效;MySQL 用 TLS/TLSRootCA。
SSLMode string `mapstructure:"ssl_mode"`
// TLS 是否对 MySQL 启用 TLS。true 时 MySQLDSN 追加 tls=true(内置:系统根 CA + 证书校验,
// ServerName 自动取自 Host)。配合 TLSRootCA 可指定私有 CA(M-config-2)。
TLS bool `mapstructure:"tls"`
// TLSRootCA MySQL TLS 自定义 CA 证书 PEM 路径(用于私有 CA/自签证书)。
// 非空时 MySQLDSN 改用 tls=MySQLTLSConfigName,由 database 包在 InitDB 时注册命名 TLS 配置
// (ServerName 取自 Host)。该命名配置仅覆盖「replica DSN host 与主库 Host 相同」的单 host 集群;
// 多 host replicas + 私有 CA 时须为每个 replica host 注册不同名 TLS 配置并自建 replica DSN(框架
// MySQLDSN 硬编码 MySQLTLSConfigName,不适用),详见 database.ensureMySQLTLSRegistered 注释。
// 空时用内置 tls=true(系统根 CA)。仅 MySQL 生效。
TLSRootCA string `mapstructure:"tls_root_ca"`
}
DatabaseConfig 数据库配置
func (*DatabaseConfig) DSN ¶
func (c *DatabaseConfig) DSN() string
DSN 根据驱动返回连接字符串。设置了 CustomDSN 时优先返回 CustomDSN。 未指定 Driver 时按 MySQL 处理;非空但未注册的 Driver 返回空字符串, 避免把拼写错误静默当作 MySQL 连接,正常加载路径会由 Validate 提前报错。
func (*DatabaseConfig) MySQLDSN ¶
func (c *DatabaseConfig) MySQLDSN() string
MySQLDSN 返回 MySQL 连接字符串。 密码经 url.QueryEscape 转义,避免含 @/:/空格 等特殊字符破坏 DSN(M9)。 loc 由 Timezone 配置,空则默认 "Local"(向后兼容)。 TLS=true 时追加 tls 参数(M-config-2):TLSRootCA 为空用内置 tls=true(系统根 CA + 证书校验); TLSRootCA 非空用 tls=MySQLTLSConfigName(database 包注册的私有 CA 命名配置)。
func (*DatabaseConfig) PostgresDSN ¶
func (c *DatabaseConfig) PostgresDSN() string
PostgresDSN 返回 PostgreSQL 连接字符串。 字符串字段统一用单引号包裹并转义,避免含空格/引号/反斜杠破坏 key=value DSN。 TimeZone 由 Timezone 配置,空则默认 "Asia/Shanghai"(向后兼容)。 sslmode 由 SSLMode 配置,空则默认 "prefer"(M-config-2:原硬编码 disable 改为 prefer,优先加密)。
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) GetStringMap ¶ added in v1.3.0
GetStringMap 获取字符串映射配置副本。
func (*Manager) GetViper ¶
GetViper 获取 viper 的只读快照。
返回值不是 Manager 内部 viper 指针;调用方修改该快照不会影响全局配置。 需要扩展配置读取时优先使用 GetString/GetInt/GetBool 等包级 helper。
func (*Manager) LoadWithWatch ¶
LoadWithWatch 加载配置文件并启用热更新
func (*Manager) RegisterCallback ¶
RegisterCallback 注册配置变更回调
func (*Manager) Reload ¶
Reload 重新加载配置文件。读取、解析、校验(C10b)任一步失败均保留旧配置并返回错误; 仅当新配置通过 Validate 后才替换 m.cfg 并触发回调。
func (*Manager) Set ¶
Set 手动设置配置。非 nil 配置会先 Validate,并以深拷贝形式保存。 H-config-1:非 nil 配置同时用其重建 m.v(不含 AutomaticEnv),使 Get() 与 GetString/GetInt/GetBool/GetViper 读到同一配置世界,消除原"Set 只更新类型化视图、 viper 视图停留在旧值"的静默分裂(违反 C1 单一配置源)。
func (*Manager) StartWatcher ¶
StartWatcher 启动配置文件监听。使用自管的 fsnotify.Watcher(监听配置文件 所在目录以兼容编辑器改写/k8s ConfigMap 原子替换),文件变更时去抖后重新加载。 幂等:重复调用不会创建多个监听 goroutine。
func (*Manager) StopWatcher ¶
func (m *Manager) StopWatcher()
StopWatcher 停止配置文件监听并释放 watcher(C10d)。幂等。 cancel ctx 与关闭 fsnotify watcher 双重退出(L-config-2),等待 watchDone 确认 goroutine 退出。
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 TraceConfig ¶ added in v1.4.0
type TraceConfig struct {
ServiceName string `mapstructure:"service_name"` // 服务名(空则回退 cfg.App.Name)
ServiceVersion string `mapstructure:"service_version"` // 服务版本
Environment string `mapstructure:"environment"` // 运行环境
ExporterType string `mapstructure:"exporter_type"` // otlp-http(默认) / otlp-grpc / stdout
Endpoint string `mapstructure:"endpoint"` // OTLP collector 地址
Insecure bool `mapstructure:"insecure"` // 明文(无 TLS)连接 collector
SampleRatio float64 `mapstructure:"sample_ratio"` // 采样比例 0.0-1.0
Enabled bool `mapstructure:"enabled"` // 是否启用导出
Propagator string `mapstructure:"propagator"` // w3c(默认) / b3 / jaeger
}
TraceConfig 链路追踪配置(OpenTelemetry)。由 App 在 WithTrace 时读取并调 trace.Init。
语义说明:OTel 的 TracerProvider / TextMapPropagator 本身是进程级全局单例 (otel.SetTracerProvider 全局生效),故 trace 不做 per-App 实例隔离--多 App 进程 共享同一 OTel 全局状态,这与 OTel 自身设计一致。App 仅负责把 trace 纳入生命周期 (Init/Close)与装入 Middleware,不提供实例隔离。
Enabled=false(默认)时 trace.Init 安装 Noop tracer,Middleware 不 panic、不导出。
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。