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 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题