This commit is contained in:
2025-03-15 10:17:07 +00:00
parent 1a53a9a8f3
commit 78f5fbf51a
24 changed files with 2915 additions and 282 deletions

View File

@@ -0,0 +1,94 @@
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/darkit/goproxy"
"github.com/darkit/goproxy/config"
"github.com/darkit/goproxy/pkg/cache"
"github.com/darkit/goproxy/pkg/healthcheck"
"github.com/darkit/goproxy/pkg/loadbalance"
"github.com/darkit/goproxy/pkg/metrics"
)
func main() {
// 创建基本配置
cfg := config.DefaultConfig()
// 配置反向代理
cfg.ReverseProxy = true // 启用反向代理模式
cfg.ListenAddr = ":8080" // 监听地址
cfg.TargetAddr = "http://example.com" // 目标地址
cfg.PreserveClientIP = true // 保留客户端IP
cfg.AddXForwardedFor = true // 添加X-Forwarded-For头
cfg.AddXRealIP = true // 添加X-Real-IP头
cfg.EnableCompression = true // 启用压缩
// 创建负载均衡器
// 根据linter错误要检查正确的API
backends := []string{
"http://server1:8080",
"http://server2:8080",
"http://server3:8080",
}
lb := loadbalance.NewRoundRobinBalancer()
// 设置后端服务器列表
lb.AddList(backends, 1)
// 健康检查配置
// 根据错误信息调整构造函数
healthCfg := &healthcheck.Config{
Interval: 10 * time.Second,
Timeout: 3 * time.Second,
MaxFails: 3,
}
// 假设NewHealthChecker只接受Config参数
healthChecker := healthcheck.NewHealthChecker(healthCfg)
// 然后单独设置后端
healthChecker.AddTargetList(backends)
// 创建缓存
// 根据错误信息修正参数
memCache := cache.NewMemoryCache(5*time.Minute, 30*time.Second, 1000)
// 使用功能选项模式创建反向代理
proxy := goproxy.NewWithOptions(
// 将配置对象传入
goproxy.WithConfig(cfg),
// 性能优化
goproxy.WithConnectionPoolSize(100),
goproxy.WithIdleTimeout(30*time.Second),
goproxy.WithRequestTimeout(10*time.Second),
// 负载均衡
goproxy.WithLoadBalancer(lb),
// 健康检查
goproxy.WithHealthChecker(healthChecker),
// 缓存
goproxy.WithHTTPCache(memCache),
// 指标收集
goproxy.WithMetrics(metrics.NewSimpleMetrics()),
// 重试策略
goproxy.WithEnableRetry(3, 1*time.Second, 10*time.Second),
// DNS缓存
goproxy.WithDNSCacheTTL(5*time.Minute),
// 启用CORS
goproxy.WithEnableCORS(true),
)
// 启动服务器
fmt.Println("反向代理启动在 :8080转发到 http://example.com 并启用负载均衡")
if err := http.ListenAndServe(":8080", proxy); err != nil {
log.Fatalf("服务器启动失败: %v", err)
}
}