Gin实现分块返回数据

package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {
		w := c.Writer
		header := w.Header()
		header.Set("Content-Type", "text/html")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(`
			<html>
					<body>
		`))
		w.(http.Flusher).Flush()
        // 这里对每次循环输出都进行Flush刷新输出
		for i := 0; i < 10; i++ {
			w.Write([]byte(fmt.Sprintf(`
				<h3>%d</h3>
			`, i)))
			//w.Flush()
			w.(http.Flusher).Flush()
			time.Sleep(time.Duration(1)*time.Second)
		}
        
		w.Write([]byte(`
			
					</body>
			</html>
		`))
		w.(http.Flusher).Flush()
	})

	r.Run()
}

posted @ 2024-08-26 17:36  朝阳1  阅读(11)  评论(0编辑  收藏  举报