如何使用Go将端口80无缝转发到端口XXXX?

huangapple go评论116阅读模式
英文:

How to pipe/forward seamlessly from port 80 to port XXXX with go?

问题

我有一堆网站在一个服务器上运行(单个IP),它们都在高端口上运行,所以我不需要root权限来运行它们。

当有人从一个网址访问,比如说,http://address001.com/,我想无缝地将数据从端口4444传输给发出此请求的人,如果有人访问http://address002.com/,我想将数据从端口5555传输。

在Go语言中,我该如何做到这一点?

到目前为止,我有一个处理函数,代码如下:

func home(w http.ResponseWriter, r *http.Request) {                      
  if strings.Contains(r.Host, "address001") {                    
    // ??? 
  }                                                                      
}
英文:

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

得分: 2

你可以使用httputil的ReverseProxy

以下是一个示例代码:

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))
}

希望对你有帮助!

英文:

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))
}

huangapple
  • 本文由 发表于 2017年8月8日 09:41:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/45558049.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定