登录
首页 >  Golang >  Go问答

解析失败导致Go代理路由失效

来源:stackoverflow

时间:2024-02-07 11:27:21 122浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《解析失败导致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://pkg.go.dev/net/http/httputil#newsinglehostreverseproxy

您没有直接使用 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)
}

理论要掌握,实操不能落!以上关于《解析失败导致Go代理路由失效》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>