向浏览器发送的大猩猩复用流数据没有逐个发送项



我正在尝试缓冲数据到浏览器。我的意图是将每件物品一个一个地发送,延迟1秒。然而,当我在浏览器中测试时,它只是等待所有延迟完成并立即显示结果。

func StreamHandler(w http.ResponseWriter, r *http.Request) {
log.Println("string handler invoked")
flusher, _ := w.(http.Flusher)
for i := 0; i < 15000; i++ {
// w.Write([]byte("Gorilla! n"))
fmt.Println(i)
fmt.Fprintf(w, "Gorilla! %v n", i)
flusher.Flush()
time.Sleep(1 * time.Second)
// time.Sleep(1 * time.Second)
}
fmt.Println("done")
}

类似的事情超级都用echo web框架做。下面的例子在echo框架使浏览器显示数据一个接一个

e.GET("/", func(c echo.Context) error {
c.Response().Header().Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
c.Response().WriteHeader(http.StatusOK)
enc := json.NewEncoder(c.Response())
for _, l := range locations {
if err := enc.Encode(l); err != nil {
return err
}
c.Response().Flush()
time.Sleep(1 * time.Second)
}
return nil
})

请帮助我使它在大猩猩框架中工作。

下面的代码可以运行

log.Println("string handler invoked")
flusher, ok := w.(http.Flusher)
if !ok {
log.Println("responseWriter is not really a flusher")
return
}
//this header had no effect
w.Header().Set("Connection", "Keep-Alive")
//these two headers are needed to get the http chunk incremently
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("X-Content-Type-Options", "nosniff")
for i := 0; i < 20; i++ {
// w.Write([]byte("Gorilla! n"))
fmt.Println(i)
fmt.Fprintf(w, "Gorilla! %v n", i)
flusher.Flush()
time.Sleep(1 * time.Second)
// time.Sleep(1 * time.Second)
}
fmt.Println("done")

最新更新