Я пытаюсь создать консоль, используя sse, которая показывает клиенту, что делает сервер. В настоящее время он делает то, что я хочу, за исключением задержки (около 2 секунд). Я добавил http.Flusher, но, похоже, ничего не делает. Я вызываю UpdateLogMessage, используя goroutines: go UpdateLogMessage("Example")
SSE:
type Upl struct {
log string
}
var Log chan *Upl
func DashboardHandler(w http.ResponseWriter, r *http.Request) {
f, ok := w.(http.Flusher)
if !ok {
fmt.Println("Streaming unsuported")
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
msg := <-Log
fmt.Fprintf(w, "data: %v\n\n", msg.log)
f.Flush()
}
//Updates log message with curent time and message content
func UpdateLogMessage(msg string) {
curentTime := time.Now().Format("15:04:05")
ul := fmt.Sprintf("<%v> %v", curentTime, msg)
up := &Upl{
log: ul,
}
Log <- up
}
func MakeChan() {
Log = make(chan *Upl)
}
Javascript:
function onLoaded(){
var source = new EventSource("sse/dashboard")
var logg = "";
var currentmsg = "";
source.onmessage = function (event){
var dashboard = event.data;
//If message changed print it to console
if (dashboard != currentmsg){
console.log("OnMessage called:");
console.dir(event);
currentmsg = dashboard;
logg += currentmsg + "<br/>";
console.log(logg);
document.getElementById("console").innerHTML = logg;
}
}
}