亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果請求在 http.Server 中超時,為什么在 Firefox 中會無限期地重復?

如果請求在 http.Server 中超時,為什么在 Firefox 中會無限期地重復?

Go
守著星空守著你 2023-07-31 17:31:05
我正在 golang 中設置一個帶有超時的簡單服務器。當運行的處理程序花費的時間超過超時時間時,如果我使用 Firefox 請求,該請求將無限期地重復。但是,如果我使用 Postman 或curl,則 reuqest 不會重復。我想防止瀏覽器中出現重復循環。我嘗試手動關閉請求正文或檢查上下文是否已取消,但是這些方法都不起作用。package mainimport (    "fmt"    "net/http"    "time")func main() {    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {        defer r.Body.Close()        fmt.Printf("Hello, you've requested: %s\n", r.URL.Path)        time.Sleep(time.Second * 2)        fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path)    })    s := http.Server{        Addr:         ":8080",        Handler:      http.DefaultServeMux,        ReadTimeout:  1 * time.Second,        WriteTimeout: 1 * time.Second,    }    s.ListenAndServe()}我希望處理程序退出并且不再重復。
查看完整描述

1 回答

?
大話西游666

TA貢獻1817條經驗 獲得超14個贊

根據我的理解,您面臨的問題是服務器超時突然關閉底層 tcp conn 而沒有編寫正確的 http 響應,同時,當 firefox 檢測到 conn 突然關閉時,它似乎決定重試 N 次,可能是因為它假設它遇到連接問題。

我相信解決方案是使用http.Handler來控制處理程序處理持續時間,并在超時到期時返回正確的 HTTP 響應。

服務器超時應該更長,并用于防止異常的客戶端行為,而不是處理程序的緩慢。

標準 HTTP 包為此目的提供了TimeoutHandler函數。

package main


import (

? ? "fmt"

? ? "net/http"

? ? "time"

)


func main() {

? ? slowHandler := func(w http.ResponseWriter, r *http.Request) {

? ? ? ? defer r.Body.Close()

? ? ? ? fmt.Printf("Hello, you've requested: %s\n", r.URL.Path)

? ? ? ? time.Sleep(time.Second * 2)

? ? ? ? fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path)

? ? }

? ? http.HandleFunc("/", slowHandler)


? ? var handler http.Handler = http.DefaultServeMux

? ? handler = http.TimeoutHandler(handler, time.Second, "processing timeout")


? ? s := http.Server{

? ? ? ? Addr:? ? ":8080",

? ? ? ? Handler: handler,

? ? ? ? // ReadTimeout:? 1 * time.Second,

? ? ? ? // WriteTimeout: 1 * time.Second,

? ? }

? ? s.ListenAndServe()

}


查看完整回答
反對 回復 2023-07-31
  • 1 回答
  • 0 關注
  • 127 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號