golang gin框架中实现"Transfer-Encoding: chunked"方式的分块发送数据到浏览器端
参考了这篇帖子:
https://golangtc.com/t/570b403eb09ecc66b90002d9
golang web如何发送小包的chunked数据
以下是代码:
r.GET("/test_stream", func(c *gin.Context){
w := c.Writer
header := w.Header()
header.Set("Transfer-Encoding", "chunked")
header.Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`
<html>
<body>
`))
w.(http.Flusher).Flush()
for i:=0 ;i<10; i++{
w.Write([]byte(fmt.Sprintf(`
<h1>%d</h1>
`,i)))
w.(http.Flusher).Flush()
time.Sleep(time.Duration(1) * time.Second)
}
w.Write([]byte(`
</body>
</html>
`))
w.(http.Flusher).Flush()
})
posted on 2020-04-06 21:25 ahfuzhang 阅读(2278) 评论(0) 编辑 收藏 举报