duangangmo0583 2018-10-31 14:40
浏览 68

无法在Linux(Mint)的goroutine中运行Go Web服务

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.

  • 写回答

1条回答 默认 最新

  • dsaj20411 2018-10-31 15:06
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog