Files
tyapi-server/internal/config/config.go

557 lines
23 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package config
import (
"time"
)
// Config 应用程序总配置
type Config struct {
Server ServerConfig `mapstructure:"server"`
Database DatabaseConfig `mapstructure:"database"`
Redis RedisConfig `mapstructure:"redis"`
Cache CacheConfig `mapstructure:"cache"`
Logger LoggerConfig `mapstructure:"logger"`
JWT JWTConfig `mapstructure:"jwt"`
API APIConfig `mapstructure:"api"`
SMS SMSConfig `mapstructure:"sms"`
Email EmailConfig `mapstructure:"email"`
Storage StorageConfig `mapstructure:"storage"`
OCR OCRConfig `mapstructure:"ocr"`
RateLimit RateLimitConfig `mapstructure:"ratelimit"`
DailyRateLimit DailyRateLimitConfig `mapstructure:"daily_ratelimit"`
Monitoring MonitoringConfig `mapstructure:"monitoring"`
Health HealthConfig `mapstructure:"health"`
Resilience ResilienceConfig `mapstructure:"resilience"`
Development DevelopmentConfig `mapstructure:"development"`
App AppConfig `mapstructure:"app"`
WechatWork WechatWorkConfig `mapstructure:"wechat_work"`
Esign EsignConfig `mapstructure:"esign"`
Wallet WalletConfig `mapstructure:"wallet"`
WestDex WestDexConfig `mapstructure:"westdex"`
Zhicha ZhichaConfig `mapstructure:"zhicha"`
Muzi MuziConfig `mapstructure:"muzi"`
AliPay AliPayConfig `mapstructure:"alipay"`
Wxpay WxpayConfig `mapstructure:"wxpay"`
WechatMini WechatMiniConfig `mapstructure:"wechat_mini"`
WechatH5 WechatH5Config `mapstructure:"wechat_h5"`
Yushan YushanConfig `mapstructure:"yushan"`
TianYanCha TianYanChaConfig `mapstructure:"tianyancha"`
Alicloud AlicloudConfig `mapstructure:"alicloud"`
Xingwei XingweiConfig `mapstructure:"xingwei"`
Jiguang JiguangConfig `mapstructure:"jiguang"`
}
// ServerConfig HTTP服务器配置
type ServerConfig struct {
Port string `mapstructure:"port"`
Mode string `mapstructure:"mode"`
Host string `mapstructure:"host"`
ReadTimeout time.Duration `mapstructure:"read_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout"`
IdleTimeout time.Duration `mapstructure:"idle_timeout"`
}
// DatabaseConfig 数据库配置
type DatabaseConfig struct {
Host string `mapstructure:"host"`
Port string `mapstructure:"port"`
User string `mapstructure:"user"`
Password string `mapstructure:"password"`
Name string `mapstructure:"name"`
SSLMode string `mapstructure:"sslmode"`
Timezone string `mapstructure:"timezone"`
MaxOpenConns int `mapstructure:"max_open_conns"`
MaxIdleConns int `mapstructure:"max_idle_conns"`
ConnMaxLifetime time.Duration `mapstructure:"conn_max_lifetime"`
AutoMigrate bool `mapstructure:"auto_migrate"`
}
// RedisConfig Redis配置
type RedisConfig struct {
Host string `mapstructure:"host"`
Port string `mapstructure:"port"`
Password string `mapstructure:"password"`
DB int `mapstructure:"db"`
PoolSize int `mapstructure:"pool_size"`
MinIdleConns int `mapstructure:"min_idle_conns"`
MaxRetries int `mapstructure:"max_retries"`
DialTimeout time.Duration `mapstructure:"dial_timeout"`
ReadTimeout time.Duration `mapstructure:"read_timeout"`
WriteTimeout time.Duration `mapstructure:"write_timeout"`
}
// CacheConfig 缓存配置
type CacheConfig struct {
DefaultTTL time.Duration `mapstructure:"default_ttl"`
CleanupInterval time.Duration `mapstructure:"cleanup_interval"`
MaxSize int `mapstructure:"max_size"`
}
// LoggerConfig 日志配置
type LoggerConfig struct {
Level string `mapstructure:"level"`
Format string `mapstructure:"format"`
Output string `mapstructure:"output"`
LogDir string `mapstructure:"log_dir"` // 日志目录
MaxSize int `mapstructure:"max_size"` // 单个文件最大大小(MB)
MaxBackups int `mapstructure:"max_backups"` // 最大备份文件数
MaxAge int `mapstructure:"max_age"` // 最大保留天数
Compress bool `mapstructure:"compress"` // 是否压缩
UseColor bool `mapstructure:"use_color"` // 是否使用彩色输出
UseDaily bool `mapstructure:"use_daily"` // 是否按日分包
// 按级别分文件配置
EnableLevelSeparation bool `mapstructure:"enable_level_separation"` // 是否启用按级别分文件
LevelConfigs map[string]LevelFileConfig `mapstructure:"level_configs"` // 各级别配置
}
// LevelFileConfig 单个级别文件配置
type LevelFileConfig struct {
MaxSize int `mapstructure:"max_size"` // 单个文件最大大小(MB)
MaxBackups int `mapstructure:"max_backups"` // 最大备份文件数
MaxAge int `mapstructure:"max_age"` // 最大保留天数
Compress bool `mapstructure:"compress"` // 是否压缩
}
// JWTConfig JWT配置
type JWTConfig struct {
Secret string `mapstructure:"secret"`
ExpiresIn time.Duration `mapstructure:"expires_in"`
RefreshExpiresIn time.Duration `mapstructure:"refresh_expires_in"`
}
// RateLimitConfig 限流配置
type RateLimitConfig struct {
Requests int `mapstructure:"requests"`
Window time.Duration `mapstructure:"window"`
Burst int `mapstructure:"burst"`
}
// DailyRateLimitConfig 每日限流配置
type DailyRateLimitConfig struct {
MaxRequestsPerDay int `mapstructure:"max_requests_per_day"` // 每日最大请求次数
MaxRequestsPerIP int `mapstructure:"max_requests_per_ip"` // 每个IP每日最大请求次数
KeyPrefix string `mapstructure:"key_prefix"` // Redis键前缀
TTL time.Duration `mapstructure:"ttl"` // 键过期时间
// 新增安全配置
EnableIPWhitelist bool `mapstructure:"enable_ip_whitelist"` // 是否启用IP白名单
IPWhitelist []string `mapstructure:"ip_whitelist"` // IP白名单
EnableIPBlacklist bool `mapstructure:"enable_ip_blacklist"` // 是否启用IP黑名单
IPBlacklist []string `mapstructure:"ip_blacklist"` // IP黑名单
EnableUserAgent bool `mapstructure:"enable_user_agent"` // 是否检查User-Agent
BlockedUserAgents []string `mapstructure:"blocked_user_agents"` // 被阻止的User-Agent
EnableReferer bool `mapstructure:"enable_referer"` // 是否检查Referer
AllowedReferers []string `mapstructure:"allowed_referers"` // 允许的Referer
EnableGeoBlock bool `mapstructure:"enable_geo_block"` // 是否启用地理位置阻止
BlockedCountries []string `mapstructure:"blocked_countries"` // 被阻止的国家/地区
EnableProxyCheck bool `mapstructure:"enable_proxy_check"` // 是否检查代理
MaxConcurrent int `mapstructure:"max_concurrent"` // 最大并发请求数
// 路径排除配置
ExcludePaths []string `mapstructure:"exclude_paths"` // 排除频率限制的路径
// 域名排除配置
ExcludeDomains []string `mapstructure:"exclude_domains"` // 排除频率限制的域名
}
// MonitoringConfig 监控配置
type MonitoringConfig struct {
MetricsEnabled bool `mapstructure:"metrics_enabled"`
MetricsPort string `mapstructure:"metrics_port"`
TracingEnabled bool `mapstructure:"tracing_enabled"`
TracingEndpoint string `mapstructure:"tracing_endpoint"`
SampleRate float64 `mapstructure:"sample_rate"`
}
// HealthConfig 健康检查配置
type HealthConfig struct {
Enabled bool `mapstructure:"enabled"`
Interval time.Duration `mapstructure:"interval"`
Timeout time.Duration `mapstructure:"timeout"`
}
// ResilienceConfig 容错配置
type ResilienceConfig struct {
CircuitBreakerEnabled bool `mapstructure:"circuit_breaker_enabled"`
CircuitBreakerThreshold int `mapstructure:"circuit_breaker_threshold"`
CircuitBreakerTimeout time.Duration `mapstructure:"circuit_breaker_timeout"`
RetryMaxAttempts int `mapstructure:"retry_max_attempts"`
RetryInitialDelay time.Duration `mapstructure:"retry_initial_delay"`
RetryMaxDelay time.Duration `mapstructure:"retry_max_delay"`
}
// DevelopmentConfig 开发配置
type DevelopmentConfig struct {
Debug bool `mapstructure:"debug"`
EnableProfiler bool `mapstructure:"enable_profiler"`
EnableCors bool `mapstructure:"enable_cors"`
CorsOrigins string `mapstructure:"cors_allowed_origins"`
CorsMethods string `mapstructure:"cors_allowed_methods"`
CorsHeaders string `mapstructure:"cors_allowed_headers"`
}
// AppConfig 应用程序配置
type AppConfig struct {
Name string `mapstructure:"name"`
Version string `mapstructure:"version"`
Env string `mapstructure:"env"`
}
// APIConfig API配置
type APIConfig struct {
Domain string `mapstructure:"domain"`
}
// SMSConfig 短信配置
type SMSConfig struct {
AccessKeyID string `mapstructure:"access_key_id"`
AccessKeySecret string `mapstructure:"access_key_secret"`
EndpointURL string `mapstructure:"endpoint_url"`
SignName string `mapstructure:"sign_name"`
TemplateCode string `mapstructure:"template_code"`
CodeLength int `mapstructure:"code_length"`
ExpireTime time.Duration `mapstructure:"expire_time"`
RateLimit SMSRateLimit `mapstructure:"rate_limit"`
MockEnabled bool `mapstructure:"mock_enabled"` // 是否启用模拟短信服务
}
// SMSRateLimit 短信限流配置
type SMSRateLimit struct {
DailyLimit int `mapstructure:"daily_limit"` // 每日发送限制
HourlyLimit int `mapstructure:"hourly_limit"` // 每小时发送限制
MinInterval time.Duration `mapstructure:"min_interval"` // 最小发送间隔
}
// EmailConfig 邮件服务配置
type EmailConfig struct {
Host string `mapstructure:"host"` // SMTP服务器地址
Port int `mapstructure:"port"` // SMTP服务器端口
Username string `mapstructure:"username"` // 邮箱用户名
Password string `mapstructure:"password"` // 邮箱密码/授权码
FromEmail string `mapstructure:"from_email"` // 发件人邮箱
UseSSL bool `mapstructure:"use_ssl"` // 是否使用SSL
Timeout time.Duration `mapstructure:"timeout"` // 超时时间
Domain string `mapstructure:"domain"` // 控制台域名
}
// GetDSN 获取数据库DSN连接字符串
func (d DatabaseConfig) GetDSN() string {
return "host=" + d.Host +
" user=" + d.User +
" password=" + d.Password +
" dbname=" + d.Name +
" port=" + d.Port +
" sslmode=" + d.SSLMode +
" TimeZone=" + d.Timezone
}
// GetRedisAddr 获取Redis地址
func (r RedisConfig) GetRedisAddr() string {
return r.Host + ":" + r.Port
}
// IsProduction 检查是否为生产环境
func (a AppConfig) IsProduction() bool {
return a.Env == "production"
}
// IsDevelopment 检查是否为开发环境
func (a AppConfig) IsDevelopment() bool {
return a.Env == "development"
}
// IsStaging 检查是否为测试环境
func (a AppConfig) IsStaging() bool {
return a.Env == "staging"
}
// WechatWorkConfig 企业微信配置
type WechatWorkConfig struct {
WebhookURL string `mapstructure:"webhook_url"`
Secret string `mapstructure:"secret"`
}
// StorageConfig 存储服务配置
type StorageConfig struct {
AccessKey string `mapstructure:"access_key"`
SecretKey string `mapstructure:"secret_key"`
Bucket string `mapstructure:"bucket"`
Domain string `mapstructure:"domain"`
}
// OCRConfig OCR服务配置
type OCRConfig struct {
APIKey string `mapstructure:"api_key"`
SecretKey string `mapstructure:"secret_key"`
}
// EsignConfig e签宝配置
type EsignConfig struct {
AppID string `mapstructure:"app_id"` // 应用ID
AppSecret string `mapstructure:"app_secret"` // 应用密钥
ServerURL string `mapstructure:"server_url"` // 服务器URL
TemplateID string `mapstructure:"template_id"` // 模板ID
Contract ContractConfig `mapstructure:"contract"` // 合同配置
Auth AuthConfig `mapstructure:"auth"` // 认证配置
Sign SignConfig `mapstructure:"sign"` // 签署配置
}
// ContractConfig 合同配置
type ContractConfig struct {
Name string `mapstructure:"name"` // 合同名称
ExpireDays int `mapstructure:"expire_days"` // 签署链接过期天数
RetryCount int `mapstructure:"retry_count"` // 重试次数
}
// AuthConfig 认证配置
type AuthConfig struct {
OrgAuthModes []string `mapstructure:"org_auth_modes"` // 机构可用认证模式
DefaultAuthMode string `mapstructure:"default_auth_mode"` // 默认认证模式
PsnAuthModes []string `mapstructure:"psn_auth_modes"` // 个人可用认证模式
WillingnessAuthModes []string `mapstructure:"willingness_auth_modes"` // 意愿认证模式
RedirectURL string `mapstructure:"redirect_url"` // 重定向URL
}
// SignConfig 签署配置
type SignConfig struct {
AutoFinish bool `mapstructure:"auto_finish"` // 是否自动完结
SignFieldStyle int `mapstructure:"sign_field_style"` // 签署区样式
ClientType string `mapstructure:"client_type"` // 客户端类型
RedirectURL string `mapstructure:"redirect_url"` // 重定向URL
}
// WalletConfig 钱包配置
type WalletConfig struct {
DefaultCreditLimit float64 `mapstructure:"default_credit_limit"`
MinAmount string `mapstructure:"min_amount"` // 最低充值金额
MaxAmount string `mapstructure:"max_amount"` // 最高充值金额
AliPayRechargeBonus []AliPayRechargeBonusRule `mapstructure:"alipay_recharge_bonus"`
BalanceAlert BalanceAlertConfig `mapstructure:"balance_alert"`
}
// BalanceAlertConfig 余额预警配置
type BalanceAlertConfig struct {
DefaultEnabled bool `mapstructure:"default_enabled"` // 默认启用余额预警
DefaultThreshold float64 `mapstructure:"default_threshold"` // 默认预警阈值
AlertCooldownHours int `mapstructure:"alert_cooldown_hours"` // 预警冷却时间(小时)
}
// AliPayRechargeBonusRule 支付宝充值赠送规则
type AliPayRechargeBonusRule struct {
RechargeAmount float64 `mapstructure:"recharge_amount"` // 充值金额
BonusAmount float64 `mapstructure:"bonus_amount"` // 赠送金额
}
// WestDexConfig 西部数据配置
type WestDexConfig struct {
URL string `mapstructure:"url"`
Key string `mapstructure:"key"`
SecretID string `mapstructure:"secret_id"`
SecretSecondID string `mapstructure:"secret_second_id"`
// 西部数据日志配置
Logging WestDexLoggingConfig `mapstructure:"logging"`
}
// WestDexLoggingConfig 西部数据日志配置
type WestDexLoggingConfig struct {
Enabled bool `mapstructure:"enabled"`
LogDir string `mapstructure:"log_dir"`
UseDaily bool `mapstructure:"use_daily"`
EnableLevelSeparation bool `mapstructure:"enable_level_separation"`
LevelConfigs map[string]WestDexLevelFileConfig `mapstructure:"level_configs"`
}
// WestDexLevelFileConfig 西部数据级别文件配置
type WestDexLevelFileConfig struct {
MaxSize int `mapstructure:"max_size"`
MaxBackups int `mapstructure:"max_backups"`
MaxAge int `mapstructure:"max_age"`
Compress bool `mapstructure:"compress"`
}
// ZhichaConfig 智查金控配置
type ZhichaConfig struct {
URL string `mapstructure:"url"`
AppID string `mapstructure:"app_id"`
AppSecret string `mapstructure:"app_secret"`
EncryptKey string `mapstructure:"encrypt_key"`
// 智查金控日志配置
Logging ZhichaLoggingConfig `mapstructure:"logging"`
}
// ZhichaLoggingConfig 智查金控日志配置
type ZhichaLoggingConfig struct {
Enabled bool `mapstructure:"enabled"`
LogDir string `mapstructure:"log_dir"`
UseDaily bool `mapstructure:"use_daily"`
EnableLevelSeparation bool `mapstructure:"enable_level_separation"`
LevelConfigs map[string]ZhichaLevelFileConfig `mapstructure:"level_configs"`
}
// ZhichaLevelFileConfig 智查金控级别文件配置
type ZhichaLevelFileConfig struct {
MaxSize int `mapstructure:"max_size"`
MaxBackups int `mapstructure:"max_backups"`
MaxAge int `mapstructure:"max_age"`
Compress bool `mapstructure:"compress"`
}
// MuziConfig 木子数据配置
type MuziConfig struct {
URL string `mapstructure:"url"`
AppID string `mapstructure:"app_id"`
AppSecret string `mapstructure:"app_secret"`
Timeout time.Duration `mapstructure:"timeout"`
Logging MuziLoggingConfig `mapstructure:"logging"`
}
// MuziLoggingConfig 木子数据日志配置
type MuziLoggingConfig struct {
Enabled bool `mapstructure:"enabled"`
LogDir string `mapstructure:"log_dir"`
UseDaily bool `mapstructure:"use_daily"`
EnableLevelSeparation bool `mapstructure:"enable_level_separation"`
LevelConfigs map[string]MuziLevelFileConfig `mapstructure:"level_configs"`
}
// MuziLevelFileConfig 木子数据日志级别配置
type MuziLevelFileConfig struct {
MaxSize int `mapstructure:"max_size"`
MaxBackups int `mapstructure:"max_backups"`
MaxAge int `mapstructure:"max_age"`
Compress bool `mapstructure:"compress"`
}
// AliPayConfig 支付宝配置
type AliPayConfig struct {
AppID string `mapstructure:"app_id"`
PrivateKey string `mapstructure:"private_key"`
AlipayPublicKey string `mapstructure:"alipay_public_key"`
IsProduction bool `mapstructure:"is_production"`
NotifyURL string `mapstructure:"notify_url"`
ReturnURL string `mapstructure:"return_url"`
}
// WxpayConfig 微信支付配置
type WxpayConfig struct {
AppID string `mapstructure:"app_id"`
MchID string `mapstructure:"mch_id"`
MchCertificateSerialNumber string `mapstructure:"mch_certificate_serial_number"`
MchApiv3Key string `mapstructure:"mch_apiv3_key"`
MchPrivateKeyPath string `mapstructure:"mch_private_key_path"`
MchPublicKeyID string `mapstructure:"mch_public_key_id"`
MchPublicKeyPath string `mapstructure:"mch_public_key_path"`
NotifyUrl string `mapstructure:"notify_url"`
RefundNotifyUrl string `mapstructure:"refund_notify_url"`
}
// WechatMiniConfig 微信小程序配置
type WechatMiniConfig struct {
AppID string `mapstructure:"app_id"`
}
// WechatH5Config 微信H5配置
type WechatH5Config struct {
AppID string `mapstructure:"app_id"`
}
// YushanConfig 羽山配置
type YushanConfig struct {
URL string `mapstructure:"url"`
APIKey string `mapstructure:"api_key"`
AcctID string `mapstructure:"acct_id"`
// 羽山日志配置
Logging YushanLoggingConfig `mapstructure:"logging"`
}
// YushanLoggingConfig 羽山日志配置
type YushanLoggingConfig struct {
Enabled bool `mapstructure:"enabled"`
LogDir string `mapstructure:"log_dir"`
UseDaily bool `mapstructure:"use_daily"`
EnableLevelSeparation bool `mapstructure:"enable_level_separation"`
LevelConfigs map[string]YushanLevelFileConfig `mapstructure:"level_configs"`
}
// YushanLevelFileConfig 羽山级别文件配置
type YushanLevelFileConfig struct {
MaxSize int `mapstructure:"max_size"`
MaxBackups int `mapstructure:"max_backups"`
MaxAge int `mapstructure:"max_age"`
Compress bool `mapstructure:"compress"`
}
// TianYanChaConfig 天眼查配置
type TianYanChaConfig struct {
BaseURL string `mapstructure:"base_url"`
APIKey string `mapstructure:"api_key"`
}
type AlicloudConfig struct {
Host string `mapstructure:"host"`
AppCode string `mapstructure:"app_code"`
}
// XingweiConfig 行为数据配置
type XingweiConfig struct {
URL string `mapstructure:"url"`
ApiID string `mapstructure:"api_id"`
ApiKey string `mapstructure:"api_key"`
// 行为数据日志配置
Logging XingweiLoggingConfig `mapstructure:"logging"`
}
// XingweiLoggingConfig 行为数据日志配置
type XingweiLoggingConfig struct {
Enabled bool `mapstructure:"enabled"`
LogDir string `mapstructure:"log_dir"`
UseDaily bool `mapstructure:"use_daily"`
EnableLevelSeparation bool `mapstructure:"enable_level_separation"`
LevelConfigs map[string]XingweiLevelFileConfig `mapstructure:"level_configs"`
}
// XingweiLevelFileConfig 行为数据级别文件配置
type XingweiLevelFileConfig struct {
MaxSize int `mapstructure:"max_size"`
MaxBackups int `mapstructure:"max_backups"`
MaxAge int `mapstructure:"max_age"`
Compress bool `mapstructure:"compress"`
}
// JiguangConfig 极光配置
type JiguangConfig struct {
URL string `mapstructure:"url"`
AppID string `mapstructure:"app_id"`
AppSecret string `mapstructure:"app_secret"`
SignMethod string `mapstructure:"sign_method"` // md5 或 hmac默认 hmac
Timeout time.Duration `mapstructure:"timeout"`
// 极光日志配置
Logging JiguangLoggingConfig `mapstructure:"logging"`
}
// JiguangLoggingConfig 极光日志配置
type JiguangLoggingConfig struct {
Enabled bool `mapstructure:"enabled"`
LogDir string `mapstructure:"log_dir"`
UseDaily bool `mapstructure:"use_daily"`
EnableLevelSeparation bool `mapstructure:"enable_level_separation"`
LevelConfigs map[string]JiguangLevelFileConfig `mapstructure:"level_configs"`
}
// JiguangLevelFileConfig 极光级别文件配置
type JiguangLevelFileConfig struct {
MaxSize int `mapstructure:"max_size"`
MaxBackups int `mapstructure:"max_backups"`
MaxAge int `mapstructure:"max_age"`
Compress bool `mapstructure:"compress"`
}
// DomainConfig 域名配置
type DomainConfig struct {
API string `mapstructure:"api"` // API域名
}