Reputation: 26004
I am trying to start two http server on different ports, but unable to use the same pattern:
handlerFunc1 := http.HandlerFunc(hello1)
http.Handle("/", handlerFunc1)
server1 := &http.Server{
Addr: "localhost:8081",
Handler: handlerFunc1,
}
go server1.ListenAndServe()
http.HandleFunc("/", hello2)
go http.ListenAndServe(":8082", nil)
Do you know how, I have tried using(as you can see) http.Server
and http.ListenAndServe
Upvotes: 1
Views: 892
Reputation: 26004
Well for any other progressive developer this works:
mux1 := http.NewServeMux()
mux1.HandleFunc("/", hello1)
go http.ListenAndServe(":8081", mux1)
mux2 := http.NewServeMux()
mux2.HandleFunc("/", hello2)
go http.ListenAndServe(":8082", mux2)
Thanks to @mkopriva's comment:
Use a different
http.ServeMux
instance for each server. The ServeMux type implements the http.Handler interface, so you can use that as the last argument tohttp.ListenAndServe
or as theHandler
field of thehttp.Server
struct. Thehttp.Handle
andhttp.HandleFunc
both use thehttp.DefaultServeMux
and the ServeMux type allows only one handler per pattern.
Upvotes: 4