Skip to content

Instantly share code, notes, and snippets.

@jpillora
Created February 21, 2016 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpillora/72c49c8e30a75d1d78b3 to your computer and use it in GitHub Desktop.
Save jpillora/72c49c8e30a75d1d78b3 to your computer and use it in GitHub Desktop.
Complete server-send events (event source) example in Go (golang)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>event source test</title>
</head>
<body>
<div id="events">
</div>
<script type="text/javascript">
console.log("hello")
var source = new EventSource("//localhost:9000/events", { withCredentials: true });
source.onmessage = function(e) {
console.log(e);
var elem = document.createElement("div");
elem.innerHTML = "event: " + e.data;
events.appendChild(elem);
window.last = e;
};
source.onerror = function(err) {
console.warn(err);
};
source.onclose = function(err) {
console.info("closed", err);
};
setTimeout(function() {
source.close();
}, 5000)
</script>
</body>
</html>
package main
import (
"log"
"net/http"
"strconv"
"time"
"gopkg.in/antage/eventsource.v1"
)
func main() {
es := eventsource.New(nil, nil)
defer es.Close()
http.Handle("/events", es)
go func() {
id := 1
for {
es.SendEventMessage("tick", "", strconv.Itoa(id))
id++
time.Sleep(1 * time.Second)
}
}()
http.Handle("/", http.FileServer(http.Dir(".")))
log.Fatal(http.ListenAndServe(":9000", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment