英文:
Gorilla mux streaming data to browser is not sending item one by one
问题
我正在尝试将数据缓冲到浏览器中。我的意图是每隔1秒发送一个项目。然而,当我在浏览器中测试时,它只是等待所有延迟完成,然后一次性显示结果。
以下是在gorilla框架中使浏览器逐个显示数据的示例:
func StreamHandler(w http.ResponseWriter, r *http.Request) {
log.Println("string handler invoked")
flusher, _ := w.(http.Flusher)
for i := 0; i < 15000; i++ {
fmt.Println(i)
fmt.Fprintf(w, "Gorilla! %v \n", i)
flusher.Flush()
time.Sleep(1 * time.Second)
}
fmt.Println("done")
}
你可以尝试将这段代码添加到你的gorilla框架中,看看是否能够按照预期逐个显示数据。
英文:
I am trying to buffer data to browser. My intention is to send each item one by one with a delay of 1 second. However when I test in browser its just wait for all the delays to complete and show the result at once.
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")
}
Similar thing is super each to do with echo web framework. following example in echo framework makes browser to show data one by one
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
})
Please help me out to make it work in gorilla framework.
答案1
得分: 1
以下是代码的翻译:
所以以下代码是有效的:
log.Println("string handler invoked")
flusher, ok := w.(http.Flusher)
if !ok {
log.Println("responseWriter is not really a flusher")
return
}
// 这个头部没有效果
w.Header().Set("Connection", "Keep-Alive")
// 这两个头部是为了逐步获取HTTP块而需要的
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")
英文:
So following code works
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论