从 Go 服务器发送分块的 HTTP 响应
解决方案:
发送分块来自Go服务器的HTTP响应并实时接收它们,需要调用写入每个数据块后的 Flusher.Flush() 。这会触发“分块”编码并立即将块发送到客户端。以下是如何实现此功能的示例:
package main 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 Trying ::1... Connected to localhost. Escape character is '^]'. GET / HTTP/1.1 HTTP/1.1 200 OK Date: Tue, 02 Jun 2015 18:16:38 GMT Content-Type: text/plain; charset=utf-8 Transfer-Encoding: chunked 9 Chunk #1 9 Chunk #2 ...
额外注:
以上是如何从 Go 服务器发送分块 HTTP 响应?的详细内容。更多信息请关注PHP中文网其他相关文章!