我有最基本的 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!"))
}
当我运行程序并localhost:5678在 Chrome 中连接时,我在控制台中得到了这个:
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 破坏它?
慕后森
红颜莎娜
Smart猫小萌
相关分类