【发布时间】:2013-08-04 03:38:21
【问题描述】:
问题是这样的:有一个网络服务器。我认为在页面加载中使用 goroutine 会很有好处,所以我继续做了:调用 loadPage 函数作为 goroutine。但是,执行此操作时,服务器会停止工作而不会出现错误。它打印一个空白的白页。问题必须出在函数本身——某些东西与 goroutine 有某种冲突。
这些是相关的功能:
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
}
【问题讨论】:
-
我看不出这些功能有什么问题。 Goroutines 就像守护线程,如果主 goroutine 退出,所有当前的 goroutines 都被杀死而没有完成。检查以确保您的主 goroutine 在此完成之前不会退出。
-
是的,这是件好事。此外,您是否尝试过不同时运行它们时会发生什么?一切正常吗?可能问题实际上并不在于在 goroutine 中运行。