Files
demo/config/unified_config.go
2025-03-15 10:17:07 +00:00

255 lines
12 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 (
"log/slog"
"time"
"github.com/darkit/goproxy/pkg/reverse"
)
// ProxyMode 代理模式
type ProxyMode string
const (
// ModeForward 正向代理模式
ModeForward ProxyMode = "forward"
// ModeReverse 反向代理模式
ModeReverse ProxyMode = "reverse"
// ModeTransparent 透明代理模式
ModeTransparent ProxyMode = "transparent"
)
// UnifiedConfig 统一代理配置
type UnifiedConfig struct {
// 基本配置
ListenAddr string `json:"listen_addr" yaml:"listen_addr" toml:"listen_addr"` // 监听地址
ProxyMode ProxyMode `json:"proxy_mode" yaml:"proxy_mode" toml:"proxy_mode"` // 代理模式forward, reverse, transparent
TargetAddr string `json:"target_addr" yaml:"target_addr" toml:"target_addr"` // 目标地址(反向代理使用)
EnableHTTPS bool `json:"enable_https" yaml:"enable_https" toml:"enable_https"` // 是否启用HTTPS
DecryptHTTPS bool `json:"decrypt_https" yaml:"decrypt_https" toml:"decrypt_https"` // 是否解密HTTPS(正向代理使用)
TLSCert string `json:"tls_cert" yaml:"tls_cert" toml:"tls_cert"` // TLS证书文件路径
TLSKey string `json:"tls_key" yaml:"tls_key" toml:"tls_key"` // TLS密钥文件路径
CACert string `json:"ca_cert" yaml:"ca_cert" toml:"ca_cert"` // CA证书文件路径(用于生成动态证书)
CAKey string `json:"ca_key" yaml:"ca_key" toml:"ca_key"` // CA密钥文件路径(用于生成动态证书)
UseECDSA bool `json:"use_ecdsa" yaml:"use_ecdsa" toml:"use_ecdsa"` // 是否使用ECDSA生成证书默认使用RSA
InsecureSkipVerify bool `json:"insecure_skip_verify" yaml:"insecure_skip_verify" toml:"insecure_skip_verify"` // 是否跳过TLS证书验证
// 连接配置
DisableKeepAlive bool `json:"disable_keep_alive" yaml:"disable_keep_alive" toml:"disable_keep_alive"` // 是否禁用连接复用
RequestTimeout time.Duration `json:"request_timeout" yaml:"request_timeout" toml:"request_timeout"` // 请求超时时间
IdleTimeout time.Duration `json:"idle_timeout" yaml:"idle_timeout" toml:"idle_timeout"` // 连接空闲超时时间
MaxIdleConns int `json:"max_idle_conns" yaml:"max_idle_conns" toml:"max_idle_conns"` // 最大空闲连接数
EnableConnectionPool bool `json:"enable_connection_pool" yaml:"enable_connection_pool" toml:"enable_connection_pool"` // 是否启用连接池
ConnectionPoolSize int `json:"connection_pool_size" yaml:"connection_pool_size" toml:"connection_pool_size"` // 连接池大小
MaxConnections int `json:"max_connections" yaml:"max_connections" toml:"max_connections"` // 最大连接数
EnableWebSocket bool `json:"enable_websocket" yaml:"enable_websocket" toml:"enable_websocket"` // 是否启用WebSocket
WebSocketIntercept bool `json:"websocket_intercept" yaml:"websocket_intercept" toml:"websocket_intercept"` // 是否拦截WebSocket
SupportWebSocketUpgrade bool `json:"support_websocket_upgrade" yaml:"support_websocket_upgrade" toml:"support_websocket_upgrade"` // 是否支持Websocket升级
// 缓存配置
EnableCache bool `json:"enable_cache" yaml:"enable_cache" toml:"enable_cache"` // 是否启用响应缓存
CacheTTL time.Duration `json:"cache_ttl" yaml:"cache_ttl" toml:"cache_ttl"` // 缓存过期时间
DNSCacheTTL time.Duration `json:"dns_cache_ttl" yaml:"dns_cache_ttl" toml:"dns_cache_ttl"` // DNS缓存过期时间
// 重试配置
EnableRetry bool `json:"enable_retry" yaml:"enable_retry" toml:"enable_retry"` // 是否启用重试机制
MaxRetries int `json:"max_retries" yaml:"max_retries" toml:"max_retries"` // 最大重试次数
RetryBackoff time.Duration `json:"retry_backoff" yaml:"retry_backoff" toml:"retry_backoff"` // 重试间隔基数
MaxRetryBackoff time.Duration `json:"max_retry_backoff" yaml:"max_retry_backoff" toml:"max_retry_backoff"` // 最大重试间隔
// HTTP头部操作
EnableCompression bool `json:"enable_compression" yaml:"enable_compression" toml:"enable_compression"` // 是否启用压缩
EnableCORS bool `json:"enable_cors" yaml:"enable_cors" toml:"enable_cors"` // 是否启用CORS
PreserveClientIP bool `json:"preserve_client_ip" yaml:"preserve_client_ip" toml:"preserve_client_ip"` // 是否保留客户端IP
RewriteHostHeader bool `json:"rewrite_host_header" yaml:"rewrite_host_header" toml:"rewrite_host_header"` // 重写Host头
AddXForwardedFor bool `json:"add_x_forwarded_for" yaml:"add_x_forwarded_for" toml:"add_x_forwarded_for"` // 是否添加X-Forwarded-For头
AddXRealIP bool `json:"add_x_real_ip" yaml:"add_x_real_ip" toml:"add_x_real_ip"` // 是否添加X-Real-IP头
// 负载均衡配置
EnableLoadBalancing bool `json:"enable_load_balancing" yaml:"enable_load_balancing" toml:"enable_load_balancing"` // 是否启用负载均衡
Backends []string `json:"backends" yaml:"backends" toml:"backends"` // 负载均衡后端列表
EnableHealthCheck bool `json:"enable_health_check" yaml:"enable_health_check" toml:"enable_health_check"` // 是否启用健康检查
HealthCheckInterval time.Duration `json:"health_check_interval" yaml:"health_check_interval" toml:"health_check_interval"` // 健康检查间隔时间
HealthCheckTimeout time.Duration `json:"health_check_timeout" yaml:"health_check_timeout" toml:"health_check_timeout"` // 健康检查超时时间
// 限流配置
EnableRateLimit bool `json:"enable_rate_limit" yaml:"enable_rate_limit" toml:"enable_rate_limit"` // 是否启用限流
RateLimit float64 `json:"rate_limit" yaml:"rate_limit" toml:"rate_limit"` // 每秒请求速率限制
MaxBurst int `json:"max_burst" yaml:"max_burst" toml:"max_burst"` // 并发请求峰值限制
// 监控和跟踪
EnableMetrics bool `json:"enable_metrics" yaml:"enable_metrics" toml:"enable_metrics"` // 是否启用监控指标
EnableTracing bool `json:"enable_tracing" yaml:"enable_tracing" toml:"enable_tracing"` // 是否启用请求追踪
// 反向代理特有配置
RulesFile string `json:"rules_file" yaml:"rules_file" toml:"rules_file"` // 规则文件路径
// 日志
Logger *slog.Logger `json:"-" yaml:"-" toml:"-"` // 日志记录器
}
// DefaultUnifiedConfig 返回默认统一配置
func DefaultUnifiedConfig() *UnifiedConfig {
return &UnifiedConfig{
ListenAddr: ":8080",
ProxyMode: ModeForward, // 默认为正向代理
DecryptHTTPS: false,
EnableHTTPS: false,
UseECDSA: false,
InsecureSkipVerify: false,
RequestTimeout: 30 * time.Second,
IdleTimeout: 90 * time.Second,
MaxIdleConns: 100,
EnableConnectionPool: true,
ConnectionPoolSize: 100,
MaxConnections: 1000,
EnableWebSocket: true,
WebSocketIntercept: false,
SupportWebSocketUpgrade: true,
EnableCache: false,
CacheTTL: 5 * time.Minute,
DNSCacheTTL: 5 * time.Minute,
EnableRetry: true,
MaxRetries: 3,
RetryBackoff: time.Second,
MaxRetryBackoff: 10 * time.Second,
EnableCompression: true,
EnableCORS: true,
PreserveClientIP: true,
RewriteHostHeader: false,
AddXForwardedFor: true,
AddXRealIP: true,
EnableLoadBalancing: false,
Backends: []string{},
EnableHealthCheck: false,
HealthCheckInterval: 30 * time.Second,
HealthCheckTimeout: 5 * time.Second,
EnableRateLimit: false,
RateLimit: 0, // 0 表示不限流
MaxBurst: 50,
EnableMetrics: false,
EnableTracing: false,
Logger: slog.Default(),
}
}
// CreateLegacyConfig 将统一配置转换为旧的配置格式(兼容性用)
func (uc *UnifiedConfig) CreateLegacyConfig() *Config {
cfg := DefaultConfig()
// 基本配置
cfg.ListenAddr = uc.ListenAddr
cfg.TargetAddr = uc.TargetAddr
cfg.DecryptHTTPS = uc.DecryptHTTPS
cfg.CACert = uc.CACert
cfg.CAKey = uc.CAKey
cfg.UseECDSA = uc.UseECDSA
cfg.TLSCert = uc.TLSCert
cfg.TLSKey = uc.TLSKey
cfg.InsecureSkipVerify = uc.InsecureSkipVerify
// 连接配置
cfg.DisableKeepAlive = uc.DisableKeepAlive
cfg.RequestTimeout = uc.RequestTimeout
cfg.EnableCache = uc.EnableCache
cfg.IdleTimeout = uc.IdleTimeout
cfg.MaxIdleConns = uc.MaxIdleConns
// 缓存配置
cfg.DNSCacheTTL = uc.DNSCacheTTL
cfg.CacheTTL = uc.CacheTTL
// 重试配置
cfg.EnableRetry = uc.EnableRetry
cfg.MaxRetries = uc.MaxRetries
cfg.BaseBackoff = uc.RetryBackoff
cfg.MaxBackoff = uc.MaxRetryBackoff
// 限流配置
cfg.RateLimit = uc.RateLimit
// 其他配置
cfg.EnableCORS = uc.EnableCORS
// 负载均衡配置
cfg.EnableLoadBalancing = uc.EnableLoadBalancing
cfg.Backends = uc.Backends
cfg.EnableRateLimit = uc.EnableRateLimit
cfg.MaxBurst = uc.MaxBurst
cfg.MaxConnections = uc.MaxConnections
cfg.EnableConnectionPool = uc.EnableConnectionPool
cfg.ConnectionPoolSize = uc.ConnectionPoolSize
cfg.EnableHealthCheck = uc.EnableHealthCheck
cfg.HealthCheckInterval = uc.HealthCheckInterval
cfg.HealthCheckTimeout = uc.HealthCheckTimeout
cfg.EnableMetrics = uc.EnableMetrics
cfg.EnableTracing = uc.EnableTracing
cfg.WebSocketIntercept = uc.WebSocketIntercept
cfg.ReverseProxy = uc.ProxyMode == ModeReverse
cfg.ReverseProxyRulesFile = uc.RulesFile
cfg.PreserveClientIP = uc.PreserveClientIP
cfg.EnableCompression = uc.EnableCompression
cfg.RewriteHostHeader = uc.RewriteHostHeader
cfg.AddXForwardedFor = uc.AddXForwardedFor
cfg.AddXRealIP = uc.AddXRealIP
cfg.SupportWebSocketUpgrade = uc.SupportWebSocketUpgrade
cfg.Logger = uc.Logger
return cfg
}
// CreateReverseConfig 将统一配置转换为反向代理配置
func (uc *UnifiedConfig) CreateReverseConfig() *reverse.Config {
cfg := reverse.DefaultConfig()
// 基础配置
cfg.BaseConfig.ListenAddr = uc.ListenAddr
cfg.BaseConfig.TargetAddr = uc.TargetAddr
cfg.BaseConfig.EnableHTTPS = uc.EnableHTTPS
if uc.TLSCert != "" && uc.TLSKey != "" {
cfg.BaseConfig.TLSConfig = &reverse.TLSConfig{
CertFile: uc.TLSCert,
KeyFile: uc.TLSKey,
InsecureSkipVerify: uc.InsecureSkipVerify,
UseECDSA: uc.UseECDSA,
}
}
cfg.BaseConfig.EnableWebSocket = uc.EnableWebSocket
cfg.BaseConfig.EnableCompression = uc.EnableCompression
cfg.BaseConfig.EnableCORS = uc.EnableCORS
cfg.BaseConfig.PreserveClientIP = uc.PreserveClientIP
cfg.BaseConfig.AddXForwardedFor = uc.AddXForwardedFor
cfg.BaseConfig.AddXRealIP = uc.AddXRealIP
// 其他配置
cfg.RulesFile = uc.RulesFile
cfg.InsecureSkipVerify = uc.InsecureSkipVerify
cfg.EnableHealthCheck = uc.EnableHealthCheck
cfg.HealthCheckInterval = uc.HealthCheckInterval
cfg.HealthCheckTimeout = uc.HealthCheckTimeout
cfg.EnableRetry = uc.EnableRetry
cfg.MaxRetries = uc.MaxRetries
cfg.RetryBackoff = uc.RetryBackoff
cfg.MaxRetryBackoff = uc.MaxRetryBackoff
cfg.EnableMetrics = uc.EnableMetrics
cfg.EnableTracing = uc.EnableTracing
cfg.WebSocketIntercept = uc.WebSocketIntercept
cfg.DNSCacheTTL = uc.DNSCacheTTL
cfg.EnableCache = uc.EnableCache
cfg.CacheTTL = uc.CacheTTL
cfg.EnableConnectionPool = uc.EnableConnectionPool
cfg.ConnectionPoolSize = uc.ConnectionPoolSize
cfg.IdleTimeout = uc.IdleTimeout
cfg.RequestTimeout = uc.RequestTimeout
return cfg
}