I am trying to learn to use server sent events (SSE) with Go. The following is the behavior that I do not understand.
What I expect (and want to implement): one message will be sent after every second; this will happen five times, and then the connection will be closed.
What actually happens: the server waits for about 5 seconds and then sends all messages at once and then the connection is closed.
Would appreciate if you can help me understand why this is happening. It is not clear to me where I am going wrong with how I am thinking about this. Every time the loop starts, it should send a message, sleep and then start a new iteration.
Thank you.
Relevant code on server
func realTimeHandler(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
i := 0
var msg string
for {
msg = fmt.Sprintf("data: Message %d\n\n", i)
i = i + 1
w.Write([]byte(msg))
time.Sleep(time.Second)
if i > 5 {
break
}
}
w.Write([]byte("data:close\n\n"))
return
}
Code on client
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>SSE</title>
</head>
<body>
<div id="realtime"></div>
<script type="text/javascript">
var evtsrc = new EventSource("/realTimeEvts");
evtsrc.onmessage = function(e) {
console.log("message received");
if (e.data == "close") {
console.log("closing connection!");
evtsrc.close();
}
console.log(e.data);
};
evtsrc.onerror = function(e) {
console.log(evtsrc.readyState);
console.log("error!");
};
</script>
</body>
</html>