I am trying to create 2 HTTP server in my go lang app and this is how I try to achieve it :
package main
import (
"net/http"
)
func main() {
server := http.Server{
Addr: ":9000",
//Handler: http.HandleFunc("/", hello)
}
server.ListenAndServe()
server2 := http.Server{
Addr: ":8000",
//Handler: http.HandleFunc("/", hello)
}
server2.ListenAndServe()
}
The issue I am having is when I go to the browser to make a request to http://localhost:9000/
it goes, but when I make a request to http://localhost:8000/
I get "Site cannot be reached". Why can't I create to instances of an HTTP server in Go?
Just like Tim Cooper was saying ListenAndServe
is blocking so the first server starts up, but then does not proceed to the second call. An easy way to fix this would be to start server
in a goroutine of its own like
func main() {
server := http.Server{
Addr: ":9000",
//Handler: http.HandleFunc("/", hello)
}
go server.ListenAndServe()
server2 := http.Server{
Addr: ":8000",
//Handler: http.HandleFunc("/", hello)
}
server2.ListenAndServe()
}