英文:
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))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论