0

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

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Chris G.
  • 23,930
  • 48
  • 177
  • 302
  • 3
    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`](https://pkg.go.dev/net/http@go1.19.2#DefaultServeMux) and the ServeMux type allows only one handler per pattern. – mkopriva Oct 24 '22 at 17:47
  • 4
    [`http.Handle`](https://cs.opensource.google/go/go/+/refs/tags/go1.19.2:src/net/http/server.go;l=2546) registers a handler on the same ([default](https://cs.opensource.google/go/go/+/refs/tags/go1.19.2:src/net/http/server.go;drc=7e72d384d66f48a78289edc6a7d1dc6ab878f990;l=2305)) [`http.ServeMux`](https://cs.opensource.google/go/go/+/refs/tags/go1.19.2:src/net/http/server.go;drc=7e72d384d66f48a78289edc6a7d1dc6ab878f990;l=2289). You'll need to create at least one custom `ServeMux`. – jub0bs Oct 24 '22 at 17:48
  • https://go.dev/play/p/oRJLRgfFBP3 – mkopriva Oct 24 '22 at 17:57
  • 2
    Remove this line `http.Handle("/", handlerFunc1)`. There's no point in registering a handler in the default serve mux when the server does not use a serve mux. – Charlie Tumahai Oct 24 '22 at 17:57

1 Answers1

3

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.

blackgreen
  • 34,072
  • 23
  • 111
  • 129
Chris G.
  • 23,930
  • 48
  • 177
  • 302