來自Go 伺服器的HTTP 區塊回應
在這個場景中,我們的目標是建立一個Go HTTP 伺服器,它會傳送一個分區塊的HTTP 回應傳輸編碼設定為「分塊」。伺服器打算以一秒的間隔寫入區塊,從而允許客戶端按需接收它們。然而,目前的實作面臨挑戰:
服務器代碼
提供的服務器代碼如下:
func HandlePost(w http.ResponseWriter, r *http.Request) { w.Header().Set("Connection", "Keep-Alive") w.Header().Set("Transfer-Encoding", "chunked") w.Header().Set("X-Content-Type-Options", "nosniff") ticker := time.NewTicker(time.Second) go func() { for t := range ticker.C { io.WriteString(w, "Chunk") fmt.Println("Tick at", t) } }() time.Sleep(time.Second * 5) ticker.Stop() fmt.Println("Finished: should return Content-Length: 0 here") w.Header().Set("Content-Length", "0") }
解決方案
解決問題:
已修訂程式碼
import ( "fmt" "io" "log" "net/http" "time" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { flusher, ok := w.(http.Flusher) if !ok { panic("expected http.ResponseWriter to be an http.Flusher") } w.Header().Set("X-Content-Type-Options", "nosniff") for i := 1; i <= 10; i++ { fmt.Fprintf(w, "Chunk #%d\n", i) flusher.Flush() // Trigger "chunked" encoding and send a chunk... time.Sleep(500 * time.Millisecond) } }) log.Print("Listening on localhost:8080") log.Fatal(http.ListenAndServe(":8080", nil)) }
驗證
使用telnet連接到伺服器:
$ telnet localhost 8080 ... HTTP/1.1 200 OK Date: ... Content-Type: text/plain; charset=utf-8 Transfer-Encoding: chunked 9 Chunk #1 9 Chunk #2 ...
使用telnet連接到伺服器:
使用telnet連接到伺服器:使用telnet連接到伺服器:使用telnet連接到伺服器:使用telnet連接到伺服器:使用telnet連接到伺服器:使用telnet連接到伺服器:每個區塊將逐步接收為伺服器發送它們。以上是為什麼我的 Go HTTP 伺服器不逐步發送分塊回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!