package main import ( "fmt" "net/http" "net/http/httptest" "os" "path/filepath" "github.com/darkit/goproxy/pkg/rewriter" ) func main2() { // 创建URL重写器 rw := rewriter.NewRewriter() // 添加一些规则 rw.AddRule("/api/v1/", "/api/v2/", false) rw.AddRuleWithDescription("/old/(.*)/page", "/new/$1/page", true, "旧页面重定向") // 从文件加载规则 exampleDir, _ := os.Getwd() jsonRulesPath := filepath.Join(exampleDir, "rules.json") textRulesPath := filepath.Join(exampleDir, "rules.txt") // 先加载JSON格式规则 fmt.Println("从JSON文件加载规则...") if err := rw.LoadRulesFromFile(jsonRulesPath); err != nil { fmt.Printf("从JSON文件加载规则失败: %v\n", err) } // 然后加载文本格式规则 fmt.Println("从文本文件加载规则...") if err := rw.LoadRulesFromFile(textRulesPath); err != nil { fmt.Printf("从文本文件加载规则失败: %v\n", err) } // 打印所有规则 fmt.Println("\n当前规则列表:") for i, rule := range rw.GetRules() { status := "启用" if !rule.Enabled { status = "禁用" } fmt.Printf("[%d] %s -> %s [%s] (%s)\n", i, rule.Pattern, rule.Replacement, map[bool]string{true: "正则", false: "前缀"}[rule.UseRegex], status) } // 测试重写 fmt.Println("\n测试URL重写:") testURLs := []string{ "/api/v1/users", "/old/profile/page", "/legacy-files/document.pdf", "/en/about/company", } for _, url := range testURLs { // 创建测试请求 req := httptest.NewRequest("GET", "http://example.com"+url, nil) // 重写URL fmt.Printf("原始URL: %s\n", req.URL.Path) rw.Rewrite(req) fmt.Printf("重写后: %s\n\n", req.URL.Path) } // 测试响应重写 fmt.Println("测试响应重写:") resp := &http.Response{ Header: http.Header{}, } resp.Header.Set("Location", "http://backend.example.com/old/profile/page") fmt.Printf("原始Location: %s\n", resp.Header.Get("Location")) rw.RewriteResponse(resp, "backend.example.com") fmt.Printf("重写后Location: %s\n", resp.Header.Get("Location")) // 保存规则到新文件 newRulesPath := filepath.Join(exampleDir, "new_rules.json") fmt.Printf("\n保存规则到文件: %s\n", newRulesPath) if err := rw.SaveRulesToFile(newRulesPath); err != nil { fmt.Printf("保存规则失败: %v\n", err) } else { fmt.Println("规则已保存") } }