douhe6255 2014-10-13 07:53
浏览 149
已采纳

Go Flush()不起作用

Please, check this gist and tell me, what's wrong?
Why I don't see my messages?
The gist: https://gist.github.com/cnaize/895f61b762a9f5ee074c

If simple, I have two functions:

func send(param martini.Params, r render.Render) {
    Ct.Msgs <- param["msg"]

    fmt.Printf("Sent: %v", param["msg"])

    r.JSON(http.StatusOK, Response{"status": "ok"})
}

And watch function:

func watch(rw http.ResponseWriter, r render.Render) {
    var msg string
    ok := true
    for ok {
        select {
        case msg, ok = <-Ct.Msgs:
            rw.Write([]byte(msg))
            fmt.Printf("Wrote: %v", msg)
            f, ok := rw.(http.Flusher)
            if ok {
                f.Flush()
                fmt.Println("Flushed")
            } else {
                r.JSON(http.StatusOK, Response{"status": "error", "descr": "CANT_FLUSH"})
                return
            }
        }
    }

    r.JSON(http.StatusOK, Response{"status": "ok", "descr": "finished"})
}

Why it doesn't work?

EDITED:

I've updated my gist. Now where are:

if i, err := rw.Write([]byte(msg)); err != nil {
    r.JSON(http.StatusOK, Response{"status": "error", "descr": err.Error()})
    return
} else {
    fmt.Printf("i: %v", i)
}

And I have in logs:

 Sent: hello
 i: 5
 Wrote: hello
 Flushed

But I see nothing.

Any ideas?

  • 写回答

1条回答 默认 最新

  • druybew06513 2014-10-13 14:51
    关注

    The flush is working. The issue is that Chrome's plain text renderer waits for the complete response body before displaying anything. Force the content type to html to see the incremental response:

    func watch(rw http.ResponseWriter, r render.Render) {
        rw.Header().Set("Content-Type", "text/html")
        // same code as before
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据