php小編草莓在解決Go代理失敗問題時,了解路由的重要性。路由是網絡通信中的核心概念,它決定了數據包應該如何從源地址傳送到目標地址。在使用Go語言進行代理時,正確配置路由非常重要。通過深入了解路由的原理和相關配置,我們可以有效解決Go代理失敗的問題,保證網絡通信的穩定性和可靠性。在本文中,我們將介紹路由的工作原理以及常見的配置方法,幫助大家更好地理解和應用路由技術。
問題內容
我有一個像這樣的簡單 go 代理。我想通過它代理請求并修改某些網站的響應。這些網站通過 tls 運行,但我的代理只是本地服務器。
func main() { target, _ := url.parse("https://www.google.com") proxy := httputil.newsinglehostreverseproxy(target) proxy.modifyresponse = rewritebody http.handle("/", proxy) http.listenandserve(":80", proxy) }
登錄后復制
結果:404錯誤,如下圖所示:
據我了解,代理服務器會發起請求并關閉請求,然后返回修改后的響應。我不確定這里會失敗。我是否遺漏了將標頭轉發到此請求失敗的地方的某些內容?
編輯
我已經讓路由正常工作了。最初,我有興趣修改響應,但除了看到 magical
標頭之外,沒有看到任何變化。
func modifyResponse() func(*http.Response) error { return func(resp *http.Response) error { resp.Header.Set("X-Proxy", "Magical") b, _ := ioutil.ReadAll(resp.Body) b = bytes.Replace(b, []byte("About"), []byte("Modified String Test"), -1) // replace html body := ioutil.NopCloser(bytes.NewReader(b)) resp.Body = body resp.ContentLength = int64(len(b)) resp.Header.Set("Content-Length", strconv.Itoa(len(b))) resp.Body.Close() return nil } } func main() { target, _ := url.Parse("https://www.google.com") proxy := httputil.NewSingleHostReverseProxy(target) director := proxy.Director proxy.Director = func(r *http.Request) { director(r) r.Host = r.URL.Hostname() } proxy.ModifyResponse = modifyResponse() http.Handle("/", proxy) http.ListenAndServe(":80", proxy) }
登錄后復制
解決方法
文檔中提到了關鍵問題,但從文檔中并不清楚如何準確處理:
newsinglehostreverseproxy 不會重寫 host 標頭。重寫
主機標頭,直接將 reverseproxy 與自定義 director 策略一起使用。
https://www.php.cn/link/747e32ab0fea7fbd2ad9ec03daa3f840
您沒有直接使用 reverseproxy
。您仍然可以使用 newsinglehostreverseproxy
并調整 director
函數,如下所示:
func main() { target, _ := url.Parse("https://www.google.com") proxy := httputil.NewSingleHostReverseProxy(target) director := proxy.Director proxy.Director = func(r *http.Request) { director(r) r.Host = r.URL.Hostname() // Adjust Host } http.Handle("/", proxy) http.ListenAndServe(":80", proxy) }
登錄后復制