Running Multiple HTTP Servers in Go made easy
In this example, I’ve demonstrated how to run multiple HTTP servers simultaneously in Go using goroutines.
- Two HTTP servers (webServer1 and webServer2) are created, each responding with a simple message.
- They are listening on different ports (8080 and 8081), which allows them to run concurrently.
- ‘go func()’ is used to start each server in its own goroutine. This allows the servers to run simultaneously without blocking each other.
- The ‘select {}’ statement is used to block the main goroutine indefinitely, ensuring that the program keeps running and the servers remain active.
package main
import (
"log"
"net/http"
)
func main() {
webServer1 := http.NewServeMux()
webServer1.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("Hello, From Web Server 1!"))
})
webServer2 := http.NewServeMux()
webServer2.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("Hello, I'm Web Server 2!"))
})
go func() {
log.Fatal(http.ListenAndServe(":8080", webServer1))
}()
go func() {
log.Fatal(http.ListenAndServe(":8081", webServer2))
}()
select {}
}
This is a simple yet effective way to handle multiple HTTP servers in Go, leveraging the power of concurrency.