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()
	})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM