doutang3815 2013-08-02 18:51
浏览 14
已采纳

Goroutines打破了程序

and I don't really know why.

The problem is this: I have, with a friend, made a web server. I figured that it would be beneficial to use goroutines in page loading, so that's what I went ahead and did: called loadPage function as a goroutine. However, when doing this, the server simply stops working without errors. It prints a blank, white page. The problem has to be in the function itself- something there is conflicting with the goroutine somehow.

These are the relevant functions:

func loadPage(w http.ResponseWriter, path string) {
   s := GetFileContent(path)
   w.Header().Add("Content-Type", getHeader(path))
   w.Header().Add("Content-Length", GetContentLength(path))
   fmt.Fprint(w, s)
}
func GetFileContent(path string) string {
   cont, err := ioutil.ReadFile(path)
   e(err)
   aob := len(cont)
   s := string(cont[:aob])
   return s
}


func GetFileContent(path string) string {
   cont, err := ioutil.ReadFile(path)
   e(err)
   aob := len(cont)
   s := string(cont[:aob])
   return s
}

func getHeader(path string) string {
   images := []string{".jpg", ".jpeg", ".gif", ".png"}
   readable := []string{".htm", ".html", ".php", ".asp", ".js", ".css"}
   if ArrayContainsSuffix(images, path) {
      return "image/jpeg"
   }
   if ArrayContainsSuffix(readable, path) {
      return "text/html"
   }
   return "file/downloadable"
}


func ArrayContainsSuffix(arr []string, c string) bool {
   length := len(arr)
   for i := 0; i < length; i++ {
      s := arr[i]
      if strings.HasSuffix(c, s) {
         return true
      }
   }
return false
}
  • 写回答

2条回答 默认 最新

  • duancai1904 2013-08-02 20:52
    关注

    The reason why this happens is because your HandlerFunc which calls "loadPage" is called synchronously with the request. When you call it in a go routine the Handler is actually returning immediately, causing the response to be sent immediately. That's why you get a blank page.

    You can see this in server.go (line 1096):

    serverHandler{c.server}.ServeHTTP(w, w.req)
    if c.hijacked() {
        return
    }
    w.finishRequest()
    

    The ServeHTTP function calls your handler, and as soon as it returns it calls "finishRequest". So your Handler function must block as long as it wants to fulfill the request.

    Using a go routine will actually not make your page any faster. Synchronizing a singe go routine with a channel, as Philip suggests, will also not help you in this case as that would be the same as not having the go routine at all.

    The root of your problem is actually ioutil.ReadFile, which buffers the entire file into memory before sending it.

    If you want to stream the file you need to use os.Open. You can use io.Copy to stream the contents of the file to the browser, which will used chunked encoding.

    That would look something like this:

    f, err := os.Open(path)
    if err != nil {
        http.Error(w, "Not Found", http.StatusNotFound)
        return
    }
    n, err := io.Copy(w, f)
    if n == 0 && err != nil {
        http.Error(w, "Error", http.StatusInternalServerError)
        return
    }
    

    If for some reason you need to do work in multiple go routines, take a look at sync.WaitGroup. Channels can also work.

    If you are trying to just serve a file, there are other options that are optimized for this, such as FileServer or ServeFile.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。