」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > Go HTTP服務器為何不漸進式發送分塊響應?

Go HTTP服務器為何不漸進式發送分塊響應?

發佈於2025-04-14
瀏覽:180

Why Doesn't My Go HTTP Server Send Chunked Responses Progressively?
http塊響應來自GO服務器

客戶端立即接收所有塊,而不是按預期逐步逐步接收。

提供的服務器代碼如下: func handlepost(w http.responsewriter,r *http.request){ w.header()。設置(“連接”,“ keep-alive”) w.header()。設置(“轉移編碼”,“塊”) w.header()。 set(“ x-content-type-options”,“ nosniff”) 股票:= time.newticker(time.second) go func(){ 對於t:= range ticker.c { io.writestring(W,“塊”) fmt.println(“ tick”,t) } }() time.sleep(time.second * 5) ticker.stop() fmt.println(“完成:應返回內容長度:0此處”) w.header()。設置(“內容長度”,“ 0”) } solution

以解決問題:

    http.ResponseWriter實現的“ flusher”接口允許我們通過調用flush flush(flush flush the Flush sending the Flush sending off flush sending)。 By adding this after each chunk is written, the client can receive chunks as they are ready.
  1. The Transfer-Encoding header is automatically managed by the HTTP writer, so setting it explicitly is unnecessary.

Revised Code

import ( “ FMT” “ io” "紀錄" “ net/http” “時間” ) func main(){ http.handlefunc(“/”,func(w http.ResponseWriter,r *http.request){ Flusher,OK:= w。 (http.flusher) 如果!好{ PANIC(“期望http.ResponseWriter成為http.flusher”) } w.header()。 set(“ x-content-type-options”,“ nosniff”) 對於I:= 1; i verification 在服務器發送時,每個塊將逐漸收到。 [&& &&&&華
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3