我正在測試http.timeoutHandler我的Go Web服務器,我注意到3秒后我的客戶端調用收到一條“ Timeout”消息,但2秒后我可以在服務器日志上看到消息“My func Println”。為什么TimeoutHandler沒有取消我的func1?這是我正在使用的代碼:package mainimport ( "fmt" "io" "net/http" "time")func func1(w http.ResponseWriter, req *http.Request) { time.Sleep(5 * time.Second) fmt.Println("My func Println") io.WriteString(w, "My func!\n")}func main() { srv := http.Server{ Addr: ":9000", WriteTimeout: 5 * time.Second, Handler: http.TimeoutHandler(http.HandlerFunc(func1), 3*time.Second, "Timeout!\n"), } if err := srv.ListenAndServe(); err != nil { fmt.Printf("Server failed: %s\n", err) }}
1 回答

眼眸繁星
TA貢獻1873條經驗 獲得超9個贊
是的,這就是它的工作原理。
當超時發生并且您的處理程序函數仍然運行(尚未返回)時,請求的上下文將被取消。您的處理程序負責監視 Context 的 Done 通道,并在請求取消時中止其工作。每個處理程序都在自己的 goroutine 中運行,并且 goroutine 不能從“外部”被終止或中斷。
如何做到這一點的示例:
func func1(w http.ResponseWriter, req *http.Request) {
select {
case <-time.After(5 * time.Second):
fmt.Println("My func Println")
io.WriteString(w, "My func!\n")
case <-req.Context().Done():
fmt.Println("Cancelled")
}
}
這將輸出:
Cancelled
如果您將處理程序中的延遲更改為 2 秒:
case <-time.After(2 * time.Second):
輸出將是:
My func Println
客戶端收到發送的數據:
My func!
- 1 回答
- 0 關注
- 153 瀏覽
添加回答
舉報
0/150
提交
取消