我正在我的http.timeoutHandlerGo Web 服務器中測試,我注意到 3 秒后我的客戶端調用收到“ Timeout”消息,但 2 秒后我可以在服務器上看到消息“我的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 回答

慕無忌1623718
TA貢獻1744條經驗 獲得超4個贊
是的,這就是它的工作方式。
當超時發生并且您的處理函數仍在運行(尚未返回)時,請求的上下文將被取消。您的處理程序負責監控 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 關注
- 179 瀏覽
添加回答
舉報
0/150
提交
取消