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

1

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())
Quent answered 17/1, 2014 at 10:12 Comment(1)
Can you provide the code you use?Sailplane
D
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

Drivein answered 17/1, 2014 at 11:9 Comment(3)
really?! thanks, that was embarrassing, I thought that is to register the multiplexer with the server not to serve "/"Quent
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{}.Volatile
@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.Drivein

© 2022 - 2024 — McMap. All rights reserved.