英文:
Virtual Hosts in Go
问题
有没有一种方法可以在单个端口(例如80)上处理多个Go Web应用程序的监听?我知道可以使用ServeMux和监听不同的主机名来实现,但是在这种方法中,它们必须在同一个程序中处理,因此是同一个二进制文件。
最好的方法是在一个二进制文件中监听:80上的主机名,然后将请求/响应写入器发送到另一个对应的二进制文件中。我可以使用"os/exec"来实现吗?如何将"Request"和"ResponseWriter"参数传递给这个外部二进制文件?提前谢谢!
编辑:
不同二进制文件的goroutine是否可以访问彼此的通道?这将是一种很酷的方法。
英文:
Is there a way to handle listening for multiple Go web applications on a single port (80, for example). I am aware of ServeMux and the ability to listen for different incoming host names, but in this method they must be handled in the same program, and thus the same binary.
Would the best method be to listen for hostnames on :80 in one binary and then send the requests/response writers to another corresponding binary somewhere else? Would I use "os/exec"
for this? How would you pass in the Request
and ResponseWriter
parameters to this external binary? Thanks in advance!
EDIT:
Is it possible for goroutines of different binary origin to access each others channels? That would be a cool way to do it.
答案1
得分: 5
通常的做法是使用反向代理来根据请求中的主机名将请求转发到相关的应用服务器(通常在不同的端口或不同的机器上运行)。
常见的方法是使用Apache来实现,但如果你想在Go中实现,可以使用net/http/httputil
包中的ReverseProxy
类型。
使用httputil.NewSingleHostReverseProxy(baseurl)
可以得到一个HTTP处理程序,它将请求代理到另一个网站并返回结果。因此,你可以通过一个多路复用的HTTP处理程序来实现前端,该处理程序根据请求的主机名将请求定向到一组ReverseProxy
处理程序中的一个。
如果你需要比NewSingleHostReverseProxy
提供的更复杂的路由功能,可以在创建代理处理程序时使用自定义的Director
函数。
英文:
The usual method for doing this would be to use a reverse proxy that directs requests to relevant app servers (usually running on a different port or different machine) based on the host name in the request.
A common approach is to use Apache for this, but if you want to do it from Go, the ReverseProxy
type from the net/http/httputil
package should help.
httputil.NewSingleHostReverseProxy(baseurl)
will give you an HTTP handler that proxies requests through to another web site and returns the results. So you could implement your front end via a multiplexing HTTP handler that directs requests to one of a number of ReverseProxy
handlers based on the requested host name.
If you need more complicated routing than NewSingleHostReverseProxy
gives you, you can use a custom Director
function when creating the proxy handler.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论