Chris G.
Chris G.

Reputation: 26004

panic: http: multiple registrations for / (root path)

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

Answers (1)

Chris G.
Chris G.

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 to http.ListenAndServe or as the Handler field of the http.Server struct. The http.Handle and http.HandleFunc both use the http.DefaultServeMux and the ServeMux type allows only one handler per pattern.

Upvotes: 4

Related Questions