【发布时间】:2015-03-14 09:27:34
【问题描述】:
我有一个最基本的 net/http 程序,用来学习 Go 中的命名空间:
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.URL)
go HandleIndex(w, r)
})
fmt.Println("Starting Server...")
log.Fatal(http.ListenAndServe(":5678", nil))
}
func HandleIndex(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte("Hello, World!"))
}
当我在 Chrome 中运行程序并连接到 localhost:5678 时,我在控制台中得到了这个:
Starting Server...
/
2015/01/15 13:41:29 http: multiple response.WriteHeader calls
/favicon.ico
2015/01/15 13:41:29 http: multiple response.WriteHeader calls
但我不明白这怎么可能。我打印 URL,启动一个新的 goroutine,编写一次标头,并给它一个静态的 Hello, World! 正文,似乎正在发生两件事之一。要么是幕后的东西正在编写另一个标头,要么以某种方式 HandleIndex 为同一个请求调用了两次。我该怎么做才能停止编写多个标题?
编辑:这似乎与go HandleIndex(w, r) 行有关,因为如果我删除go 并使其成为函数调用而不是goroutine,我不会遇到任何问题并且浏览器会获取它的数据.由于它是一个 goroutine,我得到了多个 WriteHeader 错误,并且浏览器没有显示“Hello World”。为什么要让这个 goroutine 破坏它?
【问题讨论】: