登录
首页 >  Golang >  Go问答

Gorilla mux 无法按顺序将项目发送到浏览器,仅能流式传输数据

来源:stackoverflow

时间:2024-02-25 12:18:21 383浏览 收藏

一分耕耘,一分收获!既然都打开这篇《Gorilla mux 无法按顺序将项目发送到浏览器,仅能流式传输数据》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我正在尝试将数据缓冲到浏览器。我的意图是延迟 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
    })

请帮助我使其在 gorilla 框架中工作。


正确答案


所以下面的代码有效

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")

好了,本文到此结束,带大家了解了《Gorilla mux 无法按顺序将项目发送到浏览器,仅能流式传输数据》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>