Running two web server at the same time in one go programm

我的未来我决定 提交于 2019-12-06 08:09:56

问题


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:


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



来源:https://stackoverflow.com/questions/21183183/running-two-web-server-at-the-same-time-in-one-go-programm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!