卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35663本站已运行398

了解路由时 Go 代理失败

了解路由时 go 代理失败

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)
}
卓越飞翔博客
上一篇: 无法使用 pgx 连接到 postgres 数据库 AWS RDS
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏