1 回答
TA贡献1803条经验 获得超3个赞
应用程序必须以文本/事件流格式编写响应:
fmt.Fprintf(w, "data: %s\n\n", <-p.logs)
还有其他问题。当客户端断开连接或写入响应时出现错误时,处理程序应退出。处理程序应在等待第一个事件之前刷新标头。这是更新后的代码:
func (p *DataPasser) handleHello(w http.ResponseWriter, r *http.Request) {
setupCORS(w, r)
w.Header().Set("Content-Type", "text/event-stream")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Internal error", 500)
return
}
flusher.Flush()
done := r.Context().Done()
defer fmt.Println("EXIT")
for {
select {
case <-done:
// the client disconnected
return
case m := <-p.logs:
if _, err := fmt.Fprintf(w, "data: %s\n\n", m); err != nil {
// Write to connection failed. Subsequent writes will probably fail.
return
}
flusher.Flush()
}
}
}
- 1 回答
- 0 关注
- 60 浏览
添加回答
举报