Server-Sent Events
Content-Type: *
A server-sent event is when a web page automatically gets updates from a server.
This was also possible before, but the web page would have to ask if any updates were available. With server-sent events, the updates come automatically.
Examples: Facebook/Twitter updates, stock price updates, news feeds, sport results, etc. https://www.w3schools.com/htmL/html5_serversentevents.asp

Receive Server-Sent Event Notifications

The EventSource object is used to receive server-sent event notifications:
1
var source = new EventSource("http://localhost:8080/handler");
2
source.onmessage = function(event) {
3
document.getElementById("result").innerHTML += event.data + "<br>";
4
};
Copied!

Check Server-Sent Events Support

1
if(typeof(EventSource) !== "undefined") {
2
// Yes! Server-sent events support!
3
// Some code.....
4
} else {
5
// Sorry! No server-sent events support..
6
}
Copied!

Server-Side Code Example

The server-side event stream syntax is simple. Set the "Content-Type" header to "text/event-stream". Now you can start sending event streams. The response messages starts with "data: " and ends with "\n\n".
1
func handler(ctx iris.Context) {
2
// It's always recommended to first check for `Flusher`
3
// compatibility in Go, you do that with:
4
flusher, ok := ctx.ResponseWriter().Flusher()
5
if !ok {
6
ctx.StopWithText(iris.StatusHTTPVersionNotSupported, "Streaming unsupported!")
7
return
8
}
9
10
ctx.ContentType("text/event-stream")
11
ctx.Header("Cache-Control", "no-cache")
12
13
now := time.Now()
14
ctx.Writef("data: The server time is: %s\n\n", now)
15
16
// Flush the data immediately instead of buffering it for later.
17
flusher.Flush()
18
}
Copied!
    Set the "Content-Type" header to "text/event-stream"
    Specify that the page should not cache
    Output the data to send (Always start with "data: ")
    Flush the output data back to the web page
Last modified 1yr ago