feat(proxy): 支持品赞分组代理与自动白名单

This commit is contained in:
yml
2026-11-19 23:42:56 +08:00
parent 61ea79c7c9
commit 44a5b6c883
24 changed files with 2253 additions and 315 deletions
+38 -17
View File
@@ -56,10 +56,23 @@ type xiaodianEmbedCacheItem struct {
expiresAt time.Time
}
// New 创建斗鱼客户端。act 决定使用哪个活动的接口参数;
// timeAPIURL 为空时回退到 constants.DefaultTimeAPI(全局共享的服务端时间接口);
// proxyURL 为可选参数,为空时直连,非空时配置 http/https/socks5 代理。
// New 创建斗鱼客户端。proxyURL 为可选参数,为空时直连。
// 代理地址无效时会记录错误并回退直连,调用方需要严格校验时应使用 NewWithProxy。
func New(act *activity.Activity, timeAPIURL string, tr *trace.Recorder, proxyURL ...string) *DouyuClient {
var effectiveProxy string
if len(proxyURL) > 0 {
effectiveProxy = proxyURL[0]
}
cli, err := NewWithProxy(act, timeAPIURL, tr, effectiveProxy)
if err != nil {
logger.LogEvent("代理", "error", "代理地址无效,客户端已回退直连: %v", err)
cli, _ = NewWithProxy(act, timeAPIURL, tr, "")
}
return cli
}
// NewWithProxy 创建斗鱼客户端并严格校验代理地址。
func NewWithProxy(act *activity.Activity, timeAPIURL string, tr *trace.Recorder, proxyURL string) (*DouyuClient, error) {
if act == nil {
act = activity.Default()
}
@@ -69,20 +82,10 @@ func New(act *activity.Activity, timeAPIURL string, tr *trace.Recorder, proxyURL
if tr == nil {
tr = &trace.Recorder{}
}
var effectiveProxy string
if len(proxyURL) > 0 {
effectiveProxy = proxyURL[0]
}
trsp := &http.Transport{
MaxConnsPerHost: 120,
MaxIdleConns: 120,
MaxIdleConnsPerHost: 80,
IdleConnTimeout: 30 * time.Second,
}
if effectiveProxy != "" {
if u, err := ParseProxyURL(effectiveProxy); err == nil && u != nil {
trsp.Proxy = http.ProxyURL(u)
}
effectiveProxy := strings.TrimSpace(proxyURL)
trsp, err := newHTTPTransport(effectiveProxy)
if err != nil {
return nil, err
}
return &DouyuClient{
Activity: act,
@@ -94,7 +97,25 @@ func New(act *activity.Activity, timeAPIURL string, tr *trace.Recorder, proxyURL
Timeout: 8 * time.Second,
Transport: trsp,
},
}, nil
}
func newHTTPTransport(proxyURL string) (*http.Transport, error) {
trsp := &http.Transport{
MaxConnsPerHost: 120,
MaxIdleConns: 120,
MaxIdleConnsPerHost: 80,
IdleConnTimeout: 30 * time.Second,
}
if strings.TrimSpace(proxyURL) == "" {
return trsp, nil
}
u, err := ParseProxyURL(proxyURL)
if err != nil {
return nil, err
}
trsp.Proxy = http.ProxyURL(u)
return trsp, nil
}
// SetProxy 运行时更新客户端使用的代理。
+9 -125
View File
@@ -2,7 +2,6 @@ package client
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
@@ -15,8 +14,6 @@ import (
"douyu_go/internal/types"
)
var ipPortRegex = regexp.MustCompile(`(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{2,5})`)
// ParseProxyURL 解析并规范化代理字符串为 *url.URL。
// 支持 http://, https://, socks5://;若未带协议头,默认补齐 http://。
func ParseProxyURL(proxyStr string) (*url.URL, error) {
@@ -41,133 +38,20 @@ func ParseProxyURL(proxyStr string) (*url.URL, error) {
return u, nil
}
// FetchProxyFromAPI 从指定的代理提供商 API 拉取一个代理 IP。
// 兼容星空代理等常见 JSON 格式,以及纯文本 IP:Port 格式。
func FetchProxyFromAPI(apiURL string) (*types.ProxyFetchResult, error) {
trimmed := strings.TrimSpace(apiURL)
// MaskProxyURL 隐藏代理地址中的用户名和密码,供日志与界面提示使用。
func MaskProxyURL(proxyStr string) string {
trimmed := strings.TrimSpace(proxyStr)
if trimmed == "" {
return nil, errors.New("代理提取 API 地址为空")
return ""
}
if !strings.HasPrefix(trimmed, "http://") && !strings.HasPrefix(trimmed, "https://") {
return nil, errors.New("代理提取 API 地址必须以 http:// 或 https:// 开头")
}
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, trimmed, nil)
u, err := ParseProxyURL(trimmed)
if err != nil {
return nil, fmt.Errorf("创建提取请求失败: %w", err)
return "<invalid-proxy>"
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")
client := &http.Client{
Timeout: 8 * time.Second,
if u.User != nil {
u.User = nil
}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("请求代理 API 失败: %w", err)
}
defer resp.Body.Close()
bodyBytes, err := io.ReadAll(io.LimitReader(resp.Body, 128*1024))
if err != nil {
return nil, fmt.Errorf("读取代理 API 响应失败: %w", err)
}
bodyStr := strings.TrimSpace(string(bodyBytes))
if bodyStr == "" {
return nil, errors.New("代理 API 返回内容为空")
}
// 尝试优先按照 JSON 结构体解析
var jsonObj struct {
Status int `json:"status"`
Code *int `json:"code"`
Info string `json:"info"`
Msg string `json:"msg"`
Data json.RawMessage `json:"data"`
}
if jsonErr := json.Unmarshal([]byte(bodyStr), &jsonObj); jsonErr == nil {
// 判断是否有错误提示
errInfo := jsonObj.Info
if errInfo == "" {
errInfo = jsonObj.Msg
}
// 星空代理成功状态为 100,其它平台通用成功状态为 0
hasSuccessStatus := jsonObj.Status == 100 || (jsonObj.Code != nil && *jsonObj.Code == 0)
hasErrorStatus := (jsonObj.Status != 0 && jsonObj.Status != 100) || (jsonObj.Code != nil && *jsonObj.Code != 0)
if hasErrorStatus && errInfo != "" {
return nil, fmt.Errorf("代理平台返回: %s (状态码=%d)", errInfo, jsonObj.Status)
}
if len(jsonObj.Data) > 0 {
// 1. 尝试解析为对象数组: [{"ip":"...", "port":"...", "prov":"...", "city":"..."}]
type nodeItem struct {
IP string `json:"ip"`
Port any `json:"port"`
Prov string `json:"prov"`
City string `json:"city"`
}
var items []nodeItem
if err := json.Unmarshal(jsonObj.Data, &items); err == nil && len(items) > 0 {
ip := strings.TrimSpace(items[0].IP)
portStr := fmt.Sprintf("%v", items[0].Port)
region := strings.TrimSpace(items[0].Prov + " " + items[0].City)
if ip != "" && portStr != "" {
return &types.ProxyFetchResult{
Success: true,
ProxyURL: fmt.Sprintf("http://%s:%s", ip, portStr),
IP: ip,
Port: portStr,
Region: region,
}, nil
}
}
// 2. 尝试解析为字符串数组: ["ip:port"]
var strArr []string
if err := json.Unmarshal(jsonObj.Data, &strArr); err == nil && len(strArr) > 0 {
if m := ipPortRegex.FindStringSubmatch(strArr[0]); len(m) == 3 {
return &types.ProxyFetchResult{
Success: true,
ProxyURL: fmt.Sprintf("http://%s:%s", m[1], m[2]),
IP: m[1],
Port: m[2],
}, nil
}
}
// 3. 尝试解析为单字符串
var singleStr string
if err := json.Unmarshal(jsonObj.Data, &singleStr); err == nil {
if m := ipPortRegex.FindStringSubmatch(singleStr); len(m) == 3 {
return &types.ProxyFetchResult{
Success: true,
ProxyURL: fmt.Sprintf("http://%s:%s", m[1], m[2]),
IP: m[1],
Port: m[2],
}, nil
}
}
}
if !hasSuccessStatus && errInfo != "" {
return nil, fmt.Errorf("代理平台提示: %s", errInfo)
}
}
// 兜底正则提取 IP:Port 文本格式
matches := ipPortRegex.FindStringSubmatch(bodyStr)
if len(matches) == 3 {
return &types.ProxyFetchResult{
Success: true,
ProxyURL: fmt.Sprintf("http://%s:%s", matches[1], matches[2]),
IP: matches[1],
Port: matches[2],
}, nil
}
return nil, fmt.Errorf("未能从 API 返回中识别出有效 IP:端口,原始返回: %s", truncateString(bodyStr, 120))
return u.String()
}
// TestProxyConnection 测试指定代理的连通性、出口公网 IP 与往返延迟。
+4 -56
View File
@@ -1,9 +1,6 @@
package client
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
@@ -44,58 +41,9 @@ func TestParseProxyURL(t *testing.T) {
}
}
func TestFetchProxyFromAPI_XKDaili(t *testing.T) {
// 模拟星空代理正常返回
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprint(w, `{ "status":100 ,"info":"成功" , "data": [{"ip": "115.230.134.174", "port": "40014", "prov": "浙江", "city": "嘉兴"}]}`)
}))
defer ts.Close()
res, err := FetchProxyFromAPI(ts.URL)
if err != nil {
t.Fatalf("FetchProxyFromAPI failed: %v", err)
}
if res.IP != "115.230.134.174" || res.Port != "40014" {
t.Fatalf("unexpected res: %+v", res)
}
if res.ProxyURL != "http://115.230.134.174:40014" {
t.Fatalf("unexpected proxy url: %s", res.ProxyURL)
}
if res.Region != "浙江 嘉兴" {
t.Fatalf("unexpected region: %s", res.Region)
}
}
func TestFetchProxyFromAPI_Error(t *testing.T) {
// 模拟星空代理未加白名单报错
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprint(w, `{ "status":211 , "info":"当前IP不在白名单内" }`)
}))
defer ts.Close()
_, err := FetchProxyFromAPI(ts.URL)
if err == nil {
t.Fatal("expected error, got nil")
}
if err.Error() != "代理平台返回: 当前IP不在白名单内 (状态码=211)" {
t.Fatalf("unexpected error string: %v", err)
}
}
func TestFetchProxyFromAPI_Text(t *testing.T) {
// 模拟纯文本返回
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "221.122.91.45:3128\r\n")
}))
defer ts.Close()
res, err := FetchProxyFromAPI(ts.URL)
if err != nil {
t.Fatalf("FetchProxyFromAPI failed: %v", err)
}
if res.ProxyURL != "http://221.122.91.45:3128" {
t.Fatalf("unexpected proxy url: %s", res.ProxyURL)
func TestMaskProxyURL(t *testing.T) {
got := MaskProxyURL("http://user:pass@127.0.0.1:8888")
if got != "http://127.0.0.1:8888" {
t.Fatalf("MaskProxyURL() = %q", got)
}
}