From 2a8cd1c42794ad00da331039fd2f0753ec44fc1d Mon Sep 17 00:00:00 2001 From: XOF Date: Mon, 15 Dec 2025 04:16:25 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=20proxy/rewriter.go?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- proxy/rewriter.go | 91 +++++++++++++++-------------------------------- 1 file changed, 29 insertions(+), 62 deletions(-) diff --git a/proxy/rewriter.go b/proxy/rewriter.go index 76755a1..69e7228 100644 --- a/proxy/rewriter.go +++ b/proxy/rewriter.go @@ -10,9 +10,10 @@ import ( type ContentRewriter struct { baseURL *url.URL + token string } -func NewContentRewriter(baseURL string) (*ContentRewriter, error) { +func NewContentRewriter(baseURL, token string) (*ContentRewriter, error) { u, err := url.Parse(baseURL) if err != nil { return nil, err @@ -20,14 +21,13 @@ func NewContentRewriter(baseURL string) (*ContentRewriter, error) { return &ContentRewriter{ baseURL: u, + token: token, }, nil } -// RewriteHTML 重写 HTML 内容中的所有 URL func (r *ContentRewriter) RewriteHTML(body []byte) ([]byte, error) { doc, err := html.Parse(bytes.NewReader(body)) if err != nil { - // 如果解析失败,使用简单的字符串替换 return r.simpleRewriteHTML(body), nil } @@ -41,16 +41,9 @@ func (r *ContentRewriter) RewriteHTML(body []byte) ([]byte, error) { return buf.Bytes(), nil } -// rewriteNode 递归重写 HTML 节点 func (r *ContentRewriter) rewriteNode(n *html.Node) { if n.Type == html.ElementNode { - // 重写需要处理的属性 - attrs := map[string]bool{ - "href": true, - "src": true, - "action": true, - "data": true, - } + attrs := map[string]bool{"href": true, "src": true, "action": true, "data": true} for i, attr := range n.Attr { if attrs[attr.Key] { @@ -59,31 +52,26 @@ func (r *ContentRewriter) rewriteNode(n *html.Node) { } } - // 处理 srcset 属性 if attr.Key == "srcset" { n.Attr[i].Val = r.rewriteSrcset(attr.Val) } - // 处理 style 属性中的 URL if attr.Key == "style" { n.Attr[i].Val = r.rewriteInlineCSS(attr.Val) } } - // 处理
标签 - 确保 action 属性存在 - if n.Data == "form" { - hasAction := false - for i, attr := range n.Attr { - if attr.Key == "action" { - hasAction = true - // 空 action 表示提交到当前页面 - if attr.Val == "" { - n.Attr[i].Val = r.rewriteURL(r.baseURL.String()) - } - break + if n.Data == "form" { + hasAction := false + for i, attr := range n.Attr { + if attr.Key == "action" { + hasAction = true + if attr.Val == "" { + n.Attr[i].Val = r.rewriteURL(r.baseURL.String()) } + break } - // 如果没有 action 属性,添加一个 + } if !hasAction { n.Attr = append(n.Attr, html.Attribute{ Key: "action", @@ -91,7 +79,7 @@ func (r *ContentRewriter) rewriteNode(n *html.Node) { }) } } - // 处理 标签 + if n.Data == "base" { for i, attr := range n.Attr { if attr.Key == "href" { @@ -100,20 +88,16 @@ func (r *ContentRewriter) rewriteNode(n *html.Node) { } } - // 处理