来自 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 ...
每个块将逐步接收为服务器发送它们。
以上是为什么我的 Go HTTP 服务器不逐步发送分块响应?的详细内容。更多信息请关注PHP中文网其他相关文章!