I'm learning about server sent events and I've a simple program that increments a counter variable and pushes to client. But I don't understand something. I'm told that data is only pushed to the client. Not pulled or requested from client. So what happens in the below code. Does the /sse/dashboard handler call itself every second. Because that's how it would appear. How does it know to continually 'call itself'? Below is my server side code, followed by my client side code:
Server Side:
package main
import (
"fmt"
"log"
"net/http"
)
var counter int
func main() {
http.Handle("/", http.FileServer(http.Dir("client")))
http.Handle("/sse/dashboard", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
counter++
fmt.Fprintf(w, "data: %v\n\n", counter)
}))
log.Fatal(http.ListenAndServe(":8080", nil))
}
Client Side:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Counter: <span id="counter_val"></span></h1>
<script>
var source = new EventSource("/sse/dashboard");
source.onmessage = function (event) {
var counter = JSON.parse(event.data);
document.getElementById("counter_val").innerHTML = counter;
}
</script>
</body>
</html>