英文:
Running two web server at the same time in one go programm
问题
在一个Go程序中,我想同时运行两个Web服务器,显然它们将在两个不同的端口上提供服务(如果需要,还可以是不同的IP地址)。问题出在对http.handle
的调用上,当我尝试为第二个服务器注册'/'
的处理程序时,它会发生panic,并且显示已经有一个与'/'
相关联的处理程序。我猜我需要创建一个mux,除了DefaultServeMux
之外,我尝试使用gorillaMux
来实现,但是无法弄清楚。
在同一个程序/进程中运行两个Web服务器是否存在根本性的问题?
为了更清楚,其中一个Web服务器被用作常规Web服务器,我需要第二个Web服务器作为RPC服务器,在集群的不同节点上运行的程序实例之间进行通信。
编辑:为了更清楚,这不是实际的代码,但是这是要点:
myMux := http.NewServeMux()
myMux.HandleFunc("/heartbeat", heartBeatHandler)
http.Handle("/", myMux)
server := &http.Server{
Addr: ":3400",
Handler: myMux,
}
go server.ListenAndServe()
gorillaMux := mux.NewRouter()
gorillaMux.HandleFunc("/", indexHandler)
gorillaMux.HandleFunc("/book", bookHandler)
http.Handle("/", gorillaMux)
server := &http.Server{
Addr: ":1234",
Handler: gorillaMux,
}
log.Fatal(server.ListenAndServe())
英文:
In a go program, I want to run two web servers at the same time,
obviously they will be serving on two different ports (and ip addresses if necessary),
the problem is with the call to http.handle
, when I try to register handler for '/' for the second server, it panics and says there is already a handler associated with '/',
I guess I need to create a mux in addition to the DefaultServeMux
and I tried to do it using the gorillaMux
but couldn't figure it out,
Is there something fundamentally wrong with running two web servers in the same program/process.
To make it more clear, one of the two web servers is a being used as a regular web server, I need the second one to act as an RPC server to communicate stuff between instances of the program running on different nodes of a cluster,
EDIT: to make it a bit more clear, this is not the actual code but it is the gist
myMux := http.NewServeMux()
myMux.HandleFunc("/heartbeat", heartBeatHandler)
http.Handle("/", myMux)
server := &http.Server{
Addr: ":3400",
Handler: myMux,
}
go server.ListenAndServe()
gorillaMux := mux.NewRouter()
gorillaMux.HandleFunc("/", indexHandler)
gorillaMux.HandleFunc("/book", bookHandler)
http.Handle("/", gorillaMux)
server := &http.Server{
Addr: ":1234",
Handler: gorillaMux,
}
log.Fatal(server.ListenAndServe())
答案1
得分: 8
我认为你只需要删除这些行:
http.Handle("/", myMux)
http.Handle("/", gorillaMux)
所有的路由已经在myMux和gorillaMux中定义好了。
请查看这个链接:http://play.golang.org/p/wqn4CZ01Z6
英文:
I think you just need remove these lines:
http.Handle("/", myMux)
http.Handle("/", gorillaMux)
All routes are already defined in myMux and gorillaMux.
Check this: http://play.golang.org/p/wqn4CZ01Z6
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论