Go Flush()不起作用 [英] Go Flush() doesn't work
问题描述
请检查这个要点告诉我,什么是错的?
为什么我看不到我的消息?
要点: 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){
pre>
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 if {
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})
}
为什么它不起作用?
编辑:
我已经更新了我的要点。
现在在哪里:
pre $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)
}
我有日志:
发送:hello
i:5
写道:hello
刷新
但是我什么都看不到。
任何想法?
冲洗工作正常。问题是Chrome的纯文本渲染器在显示任何内容之前会等待完整的响应主体。强制内容类型为html以查看增量响应:
func watch(rw http.ResponseWriter,r render.Render){
rw.Header()。Set(Content-Type,text / html)
//和前面相同的代码
}
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?
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
}
这篇关于Go Flush()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!