搜尋
首頁後端開發Golang為什麼 net/http 不考慮超過 30 秒的超時持續時間?

为什么 net/http 不考虑超过 30 秒的超时持续时间?

php小編香蕉在探討網路請求中的超時持續時間時發現,為什麼net/http在設計上沒有考慮超過30秒的超時時間限制?超時時間是指在發送請求後,如果在指定時間內沒有收到回應,就會認為請求失敗。在網路請求中,逾時時間的設定是非常重要的,過短可能導致請求失敗,過長則會浪費資源。透過分析,主要原因是在設計時考慮了效能和資源的平衡,以及網路環境的不確定性。接下來,我們將詳細解答這個問題。

問題內容

使用 golang 1.20.1。

在golang的net/http和context套件中,我無法設定超過三十秒的超時。設定較短的超時效果很好,例如

程式碼:

log.infof("elasticsearch url is %v", elasticsearchurl)
    client := &http.client{timeout: time.duration(time.second * 60)}
    req, err := http.newrequest("get", listbackupsurl, nil)
    if err != nil {
        internalerror(w, fmt.sprintf("error creating request: %v", err))
        return
    }
    req.setbasicauth(username, password)
    resp, err := client.do(req)
    if err != nil {
        // handle error
        internalerror(w, fmt.sprintf("error accessing elasticsearch: %v", err))
        return
    }

紀錄:

i0503 23:01:55.973821       1 somecode.go:85] url is http://elasticsearch.example.ingest:9200
e0503 23:02:25.976345       1 caller_handler.go:63] 500 internal server error: error accessing elasticsearch: get "http://elasticsearch.example.ingest:9200/_cat/snapshots/object-store-repo?v&s=id": dial tcp 1.2.3.4:9200: i/o timeout

超時時間是三十秒,而不是六十秒。

如果我使用 http.newrequestwithcontext(...) 並且使用設定相同逾時的上下文,我會得到相同的行為:

程式碼:

log.infof("elasticsearch url is %v", elasticsearchurl)
    ctx, cancel := context.withtimeout(context.background(), time.duration(time.second * 60)) 
    defer cancel()
    req, err := http.newrequestwithcontext(ctx, "get", listbackupsurl, nil)
    if err != nil {
        internalerror(w, fmt.sprintf("error creating request: %v", err))
        return
    }
    req.setbasicauth(username, password)
    resp, err := client.do(req)
    if err != nil {
        // handle error
        internalerror(w, fmt.sprintf("error accessing elasticsearch: %v", err))
        return
    }

紀錄:

i0503 23:31:10.941169       1 somecode.go:85] elasticsearch url is http://elasticsearch.example.ingest:9200
e0503 23:31:40.941642       1 caller_handler.go:63] 500 internal server error: error accessing elasticsearch: get "http://elasticsearch.example.ingest:9200/_cat/snapshots/object-store-repo?v&s=id": dial tcp 1.2.3.4:9200: i/o timeout

但是,如果我在任一方法中將超時更改為三秒 (time.duration(time.second * 3)),它將按預期工作:

I0503 23:44:17.622121       1 somecode.go:85] Elasticsearch URL is http://elasticsearch.example.ingest:9200
E0503 23:44:20.624795       1 caller_handler.go:63] 500 Internal Server Error: error accessing elasticsearch: Get "http://elasticsearch.example.ingest:9200/_cat/snapshots/object-store-repo?v&s=id": context deadline exceeded (Client.Timeout exceeded while awaiting headers)

解決方法

我會隔離問題以消除可能性,從而幫助縮小導致問題發生的原因。如果可能,請使用一小段程式碼,這樣您就可以只處理您想要的內容。

要測試您的基礎設施,httpstat 將協助您模擬遠端逾時。範例:

func main() {

    client := &http.Client{Timeout: time.Duration(time.Second * 200)}
    req, err := http.NewRequest("GET", "https://www.php.cn/link/1a59ef90d1ea801448e1567d0896a99f/504?sleep=120000", nil)
    if err != nil {
        log.Fatal(err)
        return
    }

    resp, err := client.Do(req)
    if err != nil {
        log.Fatal(err)
        return
    }

    fmt.Println(resp)
}

如果您此時收到 dial tcp ip:port: i/o timeout timeout,那麼您需要檢查您的作業系統和防火牆。無論您在 go 中設定什麼逾時,都應該覆蓋作業系統預設值,如果您以這種方式超時,則可能是防火牆(本地或遠端)導致了這種情況。

或者,如果您能夠從外部連接,則 es 可能會超時,儘管根據文檔,您應該預期會直接來自 es 的資訊錯誤。您可以直接在 url 中設定 es 的逾時 並對其進行測試。

希望這有幫助。

以上是為什麼 net/http 不考慮超過 30 秒的超時持續時間?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
在Golang和Python之間進行選擇:適合您的項目在Golang和Python之間進行選擇:適合您的項目Apr 19, 2025 am 12:21 AM

golangisidealforperformance-Critical-clitageAppations and ConcurrentPrompromming,而毛皮刺激性,快速播種和可及性。 1)forhigh-porformanceneeds,pelectgolangduetoitsefefsefefseffifeficefsefeflicefsiveficefsiveandconcurrencyfeatures.2)fordataa-fordataa-fordata-fordata-driventriventriventriventriventrivendissp pynonnononesp

Golang:並發和行動績效Golang:並發和行動績效Apr 19, 2025 am 12:20 AM

Golang通過goroutine和channel實現高效並發:1.goroutine是輕量級線程,使用go關鍵字啟動;2.channel用於goroutine間安全通信,避免競態條件;3.使用示例展示了基本和高級用法;4.常見錯誤包括死鎖和數據競爭,可用gorun-race檢測;5.性能優化建議減少channel使用,合理設置goroutine數量,使用sync.Pool管理內存。

Golang vs. Python:您應該學到哪種語言?Golang vs. Python:您應該學到哪種語言?Apr 19, 2025 am 12:20 AM

Golang更適合系統編程和高並發應用,Python更適合數據科學和快速開發。 1)Golang由Google開發,靜態類型,強調簡潔性和高效性,適合高並發場景。 2)Python由GuidovanRossum創造,動態類型,語法簡潔,應用廣泛,適合初學者和數據處理。

Golang vs. Python:性能和可伸縮性Golang vs. Python:性能和可伸縮性Apr 19, 2025 am 12:18 AM

Golang在性能和可擴展性方面優於Python。 1)Golang的編譯型特性和高效並發模型使其在高並發場景下表現出色。 2)Python作為解釋型語言,執行速度較慢,但通過工具如Cython可優化性能。

Golang vs.其他語言:比較Golang vs.其他語言:比較Apr 19, 2025 am 12:11 AM

Go語言在並發編程、性能、學習曲線等方面有獨特優勢:1.並發編程通過goroutine和channel實現,輕量高效。 2.編譯速度快,運行性能接近C語言。 3.語法簡潔,學習曲線平緩,生態系統豐富。

Golang和Python:了解差異Golang和Python:了解差異Apr 18, 2025 am 12:21 AM

Golang和Python的主要區別在於並發模型、類型系統、性能和執行速度。 1.Golang使用CSP模型,適用於高並發任務;Python依賴多線程和GIL,適合I/O密集型任務。 2.Golang是靜態類型,Python是動態類型。 3.Golang編譯型語言執行速度快,Python解釋型語言開發速度快。

Golang vs.C:評估速度差Golang vs.C:評估速度差Apr 18, 2025 am 12:20 AM

Golang通常比C 慢,但Golang在並發編程和開發效率上更具優勢:1)Golang的垃圾回收和並發模型使其在高並發場景下表現出色;2)C 通過手動內存管理和硬件優化獲得更高性能,但開發複雜度較高。

Golang:雲計算和DevOps的關鍵語言Golang:雲計算和DevOps的關鍵語言Apr 18, 2025 am 12:18 AM

Golang在雲計算和DevOps中的應用廣泛,其優勢在於簡單性、高效性和並發編程能力。 1)在雲計算中,Golang通過goroutine和channel機制高效處理並發請求。 2)在DevOps中,Golang的快速編譯和跨平台特性使其成為自動化工具的首選。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具