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 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧