3

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())
Ali
  • 18,665
  • 21
  • 103
  • 138

1 Answers1

8

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

jurka
  • 12,945
  • 3
  • 22
  • 20
  • really?! thanks, that was embarrassing, I thought that is to register the multiplexer with the server not to serve "/" – Ali Jan 17 '14 at 11:58
  • 1
    I would update your example to be a bit more idiomatic; in particular the errors need to be checked and it's hard to see the difference between the first and second server. Probably the most straightforward way to do something like this is to make two separate functions, one for each server, which registers and then serves (checking the errors!). Main then finishes with the two go statements and a terminal select{}. – Kyle Lemons Jan 27 '14 at 03:17
  • 1
    @kyle-lemons I am agree with you and even more, I think that Go needs much more **best-practice** examples which can teach how to do things in high quality manner. – jurka Jan 28 '14 at 16:44