修改成redis

This commit is contained in:
2026-04-20 18:26:54 +08:00
parent e944a25e56
commit a9cb0b2481
17 changed files with 2408 additions and 933 deletions
+9 -2
View File
@@ -13,7 +13,8 @@ import (
"sync" // 互斥锁(保护限流表和 robots.txt 缓存)
"time" // 时间(限流间隔计算、robots.txt 缓存过期)
"golang.org/x/net/html/charset" // HTML 字符集自动检测(将各种编码转为 UTF-8)
"golang.org/x/net/html/charset" // HTML 字符集自动检测(将各种编码转为 UTF-8)
"golang.org/x/text/encoding/simplifiedchinese" // GBK → UTF-8 转换兜底
)
// ErrCrawl 表示爬取过程中的预期错误(404、被 robots.txt 禁止、非 HTML 类型等)。
@@ -341,11 +342,17 @@ func decodeBody(r io.Reader, contentType string, sizeLimit int) (string, error)
// 使用 golang.org/x/net/html/charset 自动检测 HTML 编码并转为 UTF-8
utf8Reader, err := charset.NewReader(reader, contentType)
if err != nil {
// 备选方案:直接以 UTF-8 读取(可能乱码但不崩溃)
// charset 检测失败时,先读取原始字节,再尝试 GBK 兜底
data, readErr := io.ReadAll(reader)
if readErr != nil {
return "", readErr
}
// 将 GBK 字节流转为 UTF-8 字符串
utf8Bytes, convErr := simplifiedchinese.GBK.NewDecoder().Bytes(data)
if convErr == nil {
return string(utf8Bytes), nil
}
// 转换失败则返回原始字节(可能乱码但不崩溃)
return string(data), nil
}
data, err := io.ReadAll(utf8Reader)