更新 proxy/handler.go

This commit is contained in:
XOF
2025-12-15 18:00:49 +08:00
parent 2b050b62c2
commit 43506ab6e1

View File

@@ -6,6 +6,7 @@ import (
"io"
"log"
"net/http"
"net/url"
"strings"
"time"
@@ -143,6 +144,35 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
defer resp.Body.Close()
// 处理 404尝试从 Referer 提取正确路径
if resp.StatusCode == 404 {
if referer := r.Header.Get("Referer"); referer != "" && strings.Contains(referer, "/p/"+token) {
if u, err := url.Parse(targetURL); err == nil && u.Host != "" {
// 直接使用原始 targetURL 的 host + path
baseURL := u.Scheme + "://" + u.Host
correctPath := u.Path
if u.RawQuery != "" {
correctPath += "?" + u.RawQuery
}
newTargetURL := baseURL + correctPath
// 避免重复请求相同 URL
if newTargetURL != targetURL {
retryReq, _ := http.NewRequest(r.Method, newTargetURL, nil)
h.setProxyHeaders(retryReq, r)
if retryResp, err := client.Do(retryReq); err == nil && retryResp.StatusCode == 200 {
resp.Body.Close()
resp = retryResp
defer resp.Body.Close()
log.Printf("404 retry success: %s -> %s", targetURL, newTargetURL)
}
}
}
}
}
body, err := h.readResponseBody(resp)
if err != nil {
log.Printf("Failed to read response: %v", err)
@@ -169,7 +199,6 @@ func (h *ProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.sendResponse(w, resp, body)
}
func (h *ProxyHandler) rewriteContent(body []byte, targetURL, contentType, token string) []byte {
rewriter, err := NewContentRewriter(targetURL, token)
if err != nil {