From 53de3e995c6382c3bfcabe8b1716a40b9ae832b0 Mon Sep 17 00:00:00 2001 From: XOF Date: Mon, 15 Dec 2025 01:20:31 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20main.go?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.go | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 main.go diff --git a/main.go b/main.go new file mode 100644 index 0000000..b0b06b2 --- /dev/null +++ b/main.go @@ -0,0 +1,89 @@ +// main.go +package main + +import ( + "log" + "net/http" + "os" + + "siteproxy/auth" + "siteproxy/cache" + "siteproxy/config" + "siteproxy/proxy" + "siteproxy/security" +) + +func main() { + // 加载配置 + cfg := config.LoadFromEnv() + + log.Printf("Starting Secure Site Proxy...") + log.Printf("Session timeout: %v", cfg.SessionTimeout) + log.Printf("Rate limit: %d requests per %v", cfg.RateLimit, cfg.RateLimitWindow) + log.Printf("Cache enabled: %v (max: %d MB)", cfg.CacheEnabled, cfg.CacheMaxSize/1024/1024) + + // 初始化组件 + sessionMgr := auth.NewSessionManager(cfg.SessionTimeout) + authMw := auth.NewAuthMiddleware(cfg.Username, cfg.Password, sessionMgr) + + validator := security.NewRequestValidator( + cfg.BlockedDomains, + cfg.BlockedCIDRs, + cfg.AllowedSchemes, + ) + + rateLimiter := security.NewRateLimiter(cfg.RateLimit, cfg.RateLimitWindow) + + var memCache *cache.MemoryCache + if cfg.CacheEnabled { + memCache = cache.NewMemoryCache(cfg.CacheMaxSize, cfg.CacheTTL) + } else { + memCache = cache.NewMemoryCache(0, 0) // 禁用缓存 + } + + proxyHandler := proxy.NewHandler( + validator, + rateLimiter, + memCache, + cfg.UserAgent, + cfg.MaxResponseSize, + ) + + statsHandler := proxy.NewStatsHandler(memCache) + + // 设置路由 + mux := http.NewServeMux() + + // 公开路由 + mux.HandleFunc("/login", authMw.Login) + mux.HandleFunc("/health", healthCheck) + + // 受保护路由 + mux.Handle("/", authMw.Require(http.HandlerFunc(proxy.ServeIndexPage))) + mux.Handle("/proxy", authMw.Require(proxyHandler)) + mux.Handle("/stats", authMw.Require(statsHandler)) + mux.HandleFunc("/logout", authMw.Logout) + + // 启动服务器 + port := getEnv("PORT", "8080") + addr := ":" + port + + log.Printf("Server listening on %s", addr) + log.Printf("Login with username: %s", cfg.Username) + + if err := http.ListenAndServe(addr, mux); err != nil { + log.Fatal(err) + } +} + +func healthCheck(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"status":"ok"}`)) +} + +func getEnv(key, defaultValue string) string { + if value := os.Getenv(key); value != "" { + return value + } + return defaultValue +}