Go中的虚拟主机

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

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.

huangapple
  • 本文由 发表于 2014年1月11日 07:18:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/21056269.html
匿名

发表评论

匿名网友

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

确定