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,86 @@
package main
import (
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/darkit/goproxy"
"github.com/darkit/goproxy/config"
)
func main() {
// 解析命令行参数
listenAddr := flag.String("listen", ":8080", "监听地址")
targetAddr := flag.String("target", "http://localhost:8080", "目标服务地址")
enableHTTPS := flag.Bool("https", false, "启用HTTPS")
certFile := flag.String("cert", "", "TLS证书文件")
keyFile := flag.String("key", "", "TLS私钥文件")
enableCache := flag.Bool("cache", false, "启用缓存")
enableCompression := flag.Bool("compression", true, "启用压缩")
enableCORS := flag.Bool("cors", false, "启用CORS")
preserveClientIP := flag.Bool("preserve-ip", true, "保留客户端IP")
addXForwardedFor := flag.Bool("x-forwarded-for", true, "添加X-Forwarded-For头")
addXRealIP := flag.Bool("x-real-ip", true, "添加X-Real-IP头")
flag.Parse()
// 创建配置
cfg := config.DefaultConfig()
// 配置反向代理
cfg.ReverseProxy = true // 启用反向代理模式
cfg.ListenAddr = *listenAddr // 监听地址
cfg.TargetAddr = *targetAddr // 目标地址
cfg.DecryptHTTPS = *enableHTTPS // 启用HTTPS
cfg.TLSCert = *certFile // 证书文件
cfg.TLSKey = *keyFile // 私钥文件
cfg.EnableCache = *enableCache // 启用缓存
cfg.EnableCompression = *enableCompression // 启用压缩
cfg.EnableCORS = *enableCORS // 启用CORS
cfg.PreserveClientIP = *preserveClientIP // 保留客户端IP
cfg.AddXForwardedFor = *addXForwardedFor // 添加X-Forwarded-For头
cfg.AddXRealIP = *addXRealIP // 添加X-Real-IP头
// 创建代理实例
proxy := goproxy.New(&goproxy.Options{
Config: cfg,
})
// 创建HTTP服务器
server := &http.Server{
Addr: *listenAddr,
Handler: proxy,
}
// 优雅退出
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
// 启动HTTP服务器
go func() {
fmt.Printf("反向代理启动在 %s转发到 %s\n", *listenAddr, *targetAddr)
var err error
if *enableHTTPS && *certFile != "" && *keyFile != "" {
err = server.ListenAndServeTLS(*certFile, *keyFile)
} else {
err = server.ListenAndServe()
}
if err != nil && err != http.ErrServerClosed {
log.Fatalf("服务器启动失败: %v\n", err)
}
}()
// 等待退出信号
<-quit
fmt.Println("服务器正在关闭...")
// 关闭服务器
server.Shutdown(nil) // 简化版不使用context
fmt.Println("服务器已关闭")
}