英文:
Go Flush() doesn't work
问题
请检查这个 gist 并告诉我,有什么问题?
为什么我看不到我的消息?
gist 链接:https://gist.github.com/cnaize/895f61b762a9f5ee074c
如果简单来说,我有两个函数:
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"})
}
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"})
}
为什么它不起作用?
编辑:
我已经更新了我的 gist。
现在有:
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)
}
在日志中我看到:
Sent: hello
i: 5
Wrote: hello
Flushed
但是我什么都看不到。
有什么想法吗?
英文:
Please, check this gist and tell me, what's wrong?
<br>
Why I don't see my messages?
<br>
The gist: https://gist.github.com/cnaize/895f61b762a9f5ee074c
<br>
<br>
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:
<br>
<br>
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
得分: 5
刷新正在工作。问题在于Chrome的纯文本渲染器在显示任何内容之前会等待完整的响应体。强制将内容类型设置为html以查看增量响应:
func watch(rw http.ResponseWriter, r render.Render) {
rw.Header().Set("Content-Type", "text/html")
// 之前的代码相同
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论