【问题标题】:GoLang Reverse Proxy Multiple Target URLs Without Appending SubpathsGoLang 反向代理多个目标 URL 而不附加子路径
【发布时间】:2019-01-27 04:48:58
【问题描述】:

我正在尝试使用net/httputil/ReverseProxy 在 Golang 中编写一个反向代理,它能够将请求转发到不同的目标 URL,而无需附加代理 URL 子路径。

例如: 如果我的代理 URL 是 PROXYURL,(没有足够的声誉来发布超过 8 个链接,甚至是假的示例链接,因此用 PROXYURL 替换链接),

我希望PROXYURL/app1 将请求转发给TARGET1/directory,我希望PROXYURL/app2 转发给TARGET2/directory2

目前,我使用 NewSingleHostReverseProxy() 创建以下 ReverseProxy http 处理程序并将它们绑定到所需的子路径(/app1/app2)。

import (
    "fmt"
    "net/http"
    "net/http/httputil"
)

func main() {
    port := "6666"
    proxy1 = httputil.NewSingleHostReverseProxy("http://target1.com/directory")
    proxy2 = httputil.NewSingleHostReverseProxy("http://target2.com/directory2")

    http.Handle("/app1", proxy1)
    http.Handle("/app2", proxy2)
    http.ListenAndServe(fmt.Sprintf(":%s", port), nil) 
}

但是,每当我运行它并向PROXYURL/app1 发送请求时,它都会代理TARGET1/directory/app1。我从 ReverseProxy 的描述中了解到,这是预期的行为(将代理 URL 的子路径附加到目标)。但是,我想知道是否可以将代理 URL 子路径 (/app1) 映射到另一个目标 URL,而无需将子路径附加到目标 URL。

总之,我想要

http://proxy.com/app1 -> http://target1.com/directory

http://proxy.com/app2 -> http://target2.com/directory2

不是(目前正在发生)

http://proxy.com/app1 -> http://target1.com/directory/app1

http://proxy.com/app2 -> http://target2.com/directory2/app2

【问题讨论】:

标签: go proxy reverse-proxy


【解决方案1】:

我发现通过提供自定义 Director 函数而不是使用 NewSingleHostReverseProxy() (https://golang.org/src/net/http/httputil/reverseproxy.go) 提供的默认函数,我能够实现我想要的行为。我通过将 req.URL.Path 设置为 target.Path 并且不附加原始 req.URL.Path 来做到这一点。除此之外,director 函数与 reverseproxy.go 中的非常相似。

【讨论】:

  • 你能显示代码吗,代理了多个服务器。
猜你喜欢
  • 1970-01-01
  • 2020-10-15
  • 2015-12-14
  • 2019-04-16
  • 1970-01-01
  • 2015-09-15
  • 2018-03-24
  • 1970-01-01
  • 2017-03-26
相关资源
最近更新 更多