I am trying to start a web server inside my go application. When I run my code on Windows everything works as expected. The application runs it starts the web server and then waits. On linux it appears to do the same thing except I am unable to access the web server.
If I start the web server without using a goroutine the server works, it's only when I use a goroutine that it fails.
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
// go startWebServer() // This only works on Windows.
// startWebServer() // This works on both Windows and Linux.
fmt.Println("Started web server...")
for {}
}
func startWebServer() {
fileServer := http.FileServer(http.Dir("./web"))
http.Handle("/web/", http.StripPrefix("/web/", fileServer))
log.Fatal(http.ListenAndServe(":8101", nil))
}
I have a simple HTML file in my web folder, any valid HTML will do.
<h1>THIS IS A TEST</h1>
Then I point the browser to http://127.0.0.1:8101/web/index.html
On Windows I get my page regardless of which method I use.
On Linux I can only get to my page if I DON'T use a goroutine.
Actually that depends on the number cores available in the CPU. That's how go routines works. In your case running the same program on Windows provide all the cores available for your go routine to run.
But when you are running your program on virtual linux OS. It will limit to less number of resource.
To check that how many cores your program is using use GOMAXPROCS on both linux and windows separately.
package main
import (
"runtime"
"fmt"
)
func getGOMAXPROCS() int {
return runtime.GOMAXPROCS(0)
}
func main() {
fmt.Printf("GOMAXPROCS is %d
", getGOMAXPROCS())
}
Working Code on Go playground
GOMAXPROCS sets the maximum number of CPUs that can be executing simultaneously and returns the previous setting. If n < 1, it does not change the current setting. The number of logical CPUs on the local machine can be queried with NumCPU. This call will go away when the scheduler improves.
Note: Also do not use never ending loop even if you want to wait for go routine use WaitGroups.