在 Go 中流式传输分块 HTTP 响应
问题陈述:
实现 Go HTTP 时发送分块响应的服务器,服务器在指定持续时间结束时一致地传递所有块而不是发送它们逐渐地。此外,即使事先不知道内容,Go 也会自动包含值大于零的 Content-Length 标头。
解决方案:
启用增量发送块并避免过早设置 Content-Length 标头,请按照以下步骤操作:
示例代码:
package main import ( "fmt" "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() 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中文网其他相关文章!