From 40024ea5e81852af819d8e1d12652ab03075e1f4 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Sun, 16 Aug 2026 03:37:36 +0800 Subject: [PATCH] feat: load proxy pool from file --- README.md | 23 ++++++ config.example.json | 1 + config.go | 168 +++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 189 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index ce01729..09c58c6 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ - 分离配置 Zen key 池与 Zen Go key 池 - 模型同时存在于两个上游时按 `prefer` 配置优先使用 Go 或 Zen(默认 Go) - 支持直连、HTTP、HTTPS、SOCKS5 和 SOCKS5H 代理 +- 支持从文本文件读取代理池,并与配置内的代理合并、去重 +- `config.json` 支持 `//` 和 `/* ... */` 注释 - 将 key 自动均衡绑定到代理,保持连接亲和性 - 使用稳定会话哈希保持同一会话的 key/proxy 亲和性,并在节点故障时自动回退 - 代理失败后自动迁移绑定,key 失败后进行短时冷却 @@ -84,6 +86,7 @@ cp config.example.json config.json "zen_keys": ["sk-your-zen-key"], "go_keys": [], "prefer": "go", + "proxyfile": "", "proxies": ["direct"], "upstream": { "zen": "https://opencode.ai/zen", @@ -120,6 +123,7 @@ cp config.example.json config.json | `zen_keys` | OpenCode Zen API key 池。允许配置多个 key。 | | `go_keys` | OpenCode Zen Go API key 池。没有 Go key 时可以使用空数组。 | | `prefer` | 模型同时存在于 Zen 与 Go 时优先使用的上游,值为 `go` 或 `zen`,默认 `go`。仅存在于某一池时不受影响。 | +| `proxyfile` | 可选代理池文件路径。相对路径以 `config.json` 所在目录为基准;内容会追加到 `proxies` 并去重。 | | `proxies` | 上游代理列表。支持 `direct`、`http://`、`https://`、`socks5://` 和 `socks5h://`。URL 可以包含代理用户名和密码。 | `server_keys` 至少需要一个值;`zen_keys` 和 `go_keys` 至少有一个池不能为空。 @@ -147,6 +151,25 @@ SOCKS5 代理示例: ] ``` +也可以从文本文件加载代理池: + +```json +{ + "proxyfile": "proxies.txt", + "proxies": ["direct"] +} +``` + +`proxies.txt` 每行填写一个代理。支持空行、以 `#`、`;` 或 `//` 开头的整行注释,也支持在代理后使用空格加这些标记写行尾注释: + +```text +# HTTP 代理 +http://user:password@127.0.0.1:7890 +socks5://127.0.0.1:1080 # 备用代理 +``` + +配置中的 `proxies` 会先加载,随后加载 `proxyfile`,重复项只保留第一次出现的位置。如果两个来源都为空,则仍使用 `direct`。`config.json` 本身支持 `//` 单行注释和 `/* ... */` 块注释;引号内的 `https://` 等内容不会被当作注释。 + ### `upstream` | 字段 | 含义 | diff --git a/config.example.json b/config.example.json index e8e1e5a..688f72e 100644 --- a/config.example.json +++ b/config.example.json @@ -4,6 +4,7 @@ "zen_keys": ["sk-your-zen-key"], "go_keys": [], "prefer": "go", + "proxyfile": "", "proxies": ["direct"], "upstream": { "zen": "https://opencode.ai/zen", diff --git a/config.go b/config.go index 4619f2f..90a300f 100644 --- a/config.go +++ b/config.go @@ -1,11 +1,15 @@ package main import ( + "bufio" + "bytes" "encoding/json" "errors" "fmt" + "io" "net/url" "os" + "path/filepath" "strings" ) @@ -15,6 +19,7 @@ type Config struct { ZenKeys []string `json:"zen_keys"` GoKeys []string `json:"go_keys"` Proxies []string `json:"proxies"` + ProxyFile string `json:"proxyfile"` Upstream UpstreamConfig `json:"upstream"` Retry RetryConfig `json:"retry"` Models ModelsConfig `json:"models"` @@ -56,9 +61,12 @@ func LoadConfig(path string) (Config, error) { if err != nil { return Config{}, fmt.Errorf("read %s: %w", path, err) } + data, err = stripJSONComments(data) + if err != nil { + return Config{}, fmt.Errorf("parse %s: %w", path, err) + } cfg := Config{ Listen: "127.0.0.1:8080", - Proxies: []string{"direct"}, Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Go: "https://opencode.ai/zen/go"}, Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300}, Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}}, @@ -66,15 +74,21 @@ func LoadConfig(path string) (Config, error) { Logging: LoggingConfig{Level: "info"}, Prefer: TierGo, } - dec := json.NewDecoder(strings.NewReader(string(data))) + dec := json.NewDecoder(bytes.NewReader(data)) dec.DisallowUnknownFields() if err := dec.Decode(&cfg); err != nil { return Config{}, fmt.Errorf("parse %s: %w", path, err) } + if err := ensureJSONEOF(dec); err != nil { + return Config{}, fmt.Errorf("parse %s: %w", path, err) + } trimList(&cfg.ServerKeys) trimList(&cfg.ZenKeys) trimList(&cfg.GoKeys) - trimList(&cfg.Proxies) + cfg.ProxyFile = strings.TrimSpace(cfg.ProxyFile) + if err := loadProxyFiles(path, &cfg); err != nil { + return Config{}, err + } if cfg.Prefer != TierZen && cfg.Prefer != TierGo { return Config{}, errors.New("prefer must be \"zen\" or \"go\"") } @@ -124,6 +138,154 @@ func LoadConfig(path string) (Config, error) { return cfg, nil } +func ensureJSONEOF(dec *json.Decoder) error { + var extra any + if err := dec.Decode(&extra); err != io.EOF { + if err == nil { + return errors.New("multiple JSON values") + } + return err + } + return nil +} + +// stripJSONComments removes // and /* */ comments without changing newlines, +// so syntax errors still point at the correct line in config.json. Comment +// markers inside JSON strings (for example, https:// URLs) are preserved. +func stripJSONComments(data []byte) ([]byte, error) { + data = bytes.TrimPrefix(data, []byte{0xef, 0xbb, 0xbf}) + out := make([]byte, 0, len(data)) + inString := false + escaped := false + lineComment := false + blockComment := false + + for i := 0; i < len(data); i++ { + current := data[i] + if lineComment { + if current == '\n' || current == '\r' { + lineComment = false + out = append(out, current) + } else { + out = append(out, ' ') + } + continue + } + if blockComment { + if current == '*' && i+1 < len(data) && data[i+1] == '/' { + out = append(out, ' ', ' ') + i++ + blockComment = false + } else if current == '\n' || current == '\r' { + out = append(out, current) + } else { + out = append(out, ' ') + } + continue + } + if inString { + out = append(out, current) + if escaped { + escaped = false + } else if current == '\\' { + escaped = true + } else if current == '"' { + inString = false + } + continue + } + + switch { + case current == '"': + inString = true + out = append(out, current) + case current == '/' && i+1 < len(data) && data[i+1] == '/': + lineComment = true + out = append(out, ' ', ' ') + i++ + case current == '/' && i+1 < len(data) && data[i+1] == '*': + blockComment = true + out = append(out, ' ', ' ') + i++ + default: + out = append(out, current) + } + } + if blockComment { + return nil, errors.New("unterminated block comment") + } + return out, nil +} + +func loadProxyFiles(configPath string, cfg *Config) error { + trimList(&cfg.Proxies) + if cfg.ProxyFile != "" { + resolved := cfg.ProxyFile + if !filepath.IsAbs(resolved) { + resolved = filepath.Join(filepath.Dir(configPath), resolved) + } + proxies, err := readProxyFile(resolved) + if err != nil { + return fmt.Errorf("load proxy file %s: %w", resolved, err) + } + cfg.Proxies = append(cfg.Proxies, proxies...) + } + + cfg.Proxies = uniqueStrings(cfg.Proxies) + if len(cfg.Proxies) == 0 { + cfg.Proxies = []string{"direct"} + } + return nil +} + +func readProxyFile(path string) ([]string, error) { + file, err := os.Open(path) + if err != nil { + return nil, err + } + defer file.Close() + + var proxies []string + scanner := bufio.NewScanner(file) + scanner.Buffer(make([]byte, 4096), 1024*1024) + for scanner.Scan() { + value := strings.TrimSpace(strings.TrimPrefix(scanner.Text(), "\ufeff")) + value = strings.TrimSpace(stripProxyLineComment(value)) + if value != "" { + proxies = append(proxies, value) + } + } + if err := scanner.Err(); err != nil { + return nil, err + } + return proxies, nil +} + +func stripProxyLineComment(line string) string { + for i := 0; i < len(line); i++ { + if i > 0 && line[i-1] != ' ' && line[i-1] != '\t' { + continue + } + if line[i] == '#' || line[i] == ';' || (line[i] == '/' && i+1 < len(line) && line[i+1] == '/') { + return line[:i] + } + } + return line +} + +func uniqueStrings(items []string) []string { + out := items[:0] + seen := make(map[string]struct{}, len(items)) + for _, item := range items { + if _, exists := seen[item]; exists { + continue + } + seen[item] = struct{}{} + out = append(out, item) + } + return out +} + func trimList(items *[]string) { out := (*items)[:0] for _, item := range *items {