donqh00404 2017-08-08 01:41
浏览 67
已采纳

如何使用go从端口80无缝地管道传输/转发到端口XXXX?

I have a bunch of websites running on one server (single IP) and they all run on high ports so I don't need root to run them.

When someone visits from one web address, lets say, http://address001.com/, I want to seamlessly pipe the data from port 4444 to the person who made this request, and if someone visits http://address002.com/ I want to pipe the data from port 5555.

How would I do this in Go?

So far I have a handler function that looks like this:

func home(w http.ResponseWriter, r *http.Request) {                      
  if strings.Contains(r.Host, "address001") {                    
    // ???
  }                                                                      
}  
  • 写回答

1条回答 默认 最新

  • dsfds656545 2017-08-08 02:12
    关注

    you can use httputil's ReverseProxy

    here's an example code

    package main
    
    import (
        "log"
        "net/http"
        "net/http/httputil"
    )
    
    func main() {
        director := func(req *http.Request) {
            switch req.Host {
            case "address001.com":
                req.URL.Host = "localhost:4444"
                req.URL.Scheme = "http"
            case "address002.com":
                req.URL.Host = "localhost:5555"
                req.URL.Scheme = "http"
            default:
                log.Println("error")
            }
        }
        proxy := &httputil.ReverseProxy{Director: director}
        log.Fatalln(http.ListenAndServe(":8080", proxy))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作