Вопрос

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())
Это было полезно?

Решение

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top