// 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 }