go - How to create many http servers into one app? -
i want create 2 http servers 1 golang app. example:
package main import ( "io" "net/http" ) func helloone(w http.responsewriter, r *http.request) { io.writestring(w, "hello world one!") } func hellotwo(w http.responsewriter, r *http.request) { io.writestring(w, "hello world two!") } func main() { // how create 2 http server instatce? http.handlefunc("/", helloone) http.handlefunc("/", hellotwo) go http.listenandserve(":8001", nil) http.listenandserve(":8002", nil) }
how create 2 http server instance , add handlers them?
you'll need create separate http.servemux
instances. calling http.listenandserve(port, nil)
uses defaultservemux
(i.e. shared). docs here: http://golang.org/pkg/net/http/#newservemux
example:
func main() { r1 := http.newservemux() r1.handlefunc("/", helloone) r2 := http.newservemux() r2.handlefunc("/", hellotwo) go func() { log.fatal(http.listenandserve(":8001", r1))}() go func() { log.fatal(http.listenandserve(":8002", r2))}() select {} }
wrapping servers log.fatal
cause program quit if 1 of listeners doesn't function. if wanted program stay if 1 of servers fails start or crashes, err := http.listenandserve(port, mux)
, handle error way.
Comments
Post a Comment