dongshan7708 2019-01-27 04:48
浏览 405
已采纳

GoLang反向代理多个目标URL,无需附加子路径

I am trying to write a reverse proxy in Golang using net/httputil/ReverseProxy that is able to forward requests to different target URLs without appending the proxy URL subpaths.

For example: If my proxy URL is PROXYURL, (not enough reputation to post more than 8 links, even fake example ones, so hence replacing link with PROXYURL),

I would like PROXYURL/app1 to forward requests to TARGET1/directory and I would like PROXYURL/app2 to forward to TARGET2/directory2

Currently, I create the following ReverseProxy http handlers using NewSingleHostReverseProxy() and bind them to the desired subpaths (/app1 and /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) 
}

However, whenever I run this and send a request to PROXYURL/app1, it proxies TARGET1/directory/app1. I understand that from the description of ReverseProxy, this is the intended behavior (appending the subpath of the proxy URL to the target). However, I was wondering if it is possible to map a proxy URL subpath (/app1) to another target URL without the subpath being appended to the target URL.

In summary, I want

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

and

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

not (as is currently happening)

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

and

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

  • 写回答

1条回答 默认 最新

  • dongmo2324 2019-01-30 05:45
    关注

    I found that by providing a custom Director function instead of using the default one provided by NewSingleHostReverseProxy() (https://golang.org/src/net/http/httputil/reverseproxy.go) , I was able to implement the behavior I wanted. I did this by setting req.URL.Path to target.Path and not appending the original req.URL.Path. Other than that, the director function was very similar to that in reverseproxy.go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配