Skip to content

Instantly share code, notes, and snippets.

@danesparza
Created February 16, 2022 14:11
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 danesparza/8c206f6f47639fc9d161fbd9e3b4ebbd to your computer and use it in GitHub Desktop.
Save danesparza/8c206f6f47639fc9d161fbd9e3b4ebbd to your computer and use it in GitHub Desktop.
Small golang / html Server Sent Events (SSE) proof of concept
<html>
<head>
<meta charset="UTF-8">
<title>Server-sent events demo</title>
</head>
<body>
<button>Close the connection</button>
<ul>
</ul>
<script>
var button = document.querySelector('button');
var evtSource = new EventSource('http://localhost:8000/');
console.log(evtSource.withCredentials);
console.log(evtSource.readyState);
console.log(evtSource.url);
var eventList = document.querySelector('ul');
evtSource.onopen = function() {
console.log("Connection to server opened.");
};
evtSource.onmessage = function(e) {
var newElement = document.createElement("li");
newElement.textContent = "message: " + e.data;
eventList.appendChild(newElement);
};
evtSource.onerror = function() {
console.log("EventSource failed.");
};
button.onclick = function() {
console.log('Connection closed');
evtSource.close();
};
// evtSource.addEventListener("ping", function(e) {
// var newElement = document.createElement("li");
//
// var obj = JSON.parse(e.data);
// newElement.innerHTML = "ping at " + obj.time;
// eventList.appendChild(newElement);
// }, false);
</script>
</body>
</html>
package main
import (
"net/http"
"time"
"github.com/rs/cors"
log "github.com/sirupsen/logrus"
"github.com/tmaxmax/go-sse"
)
func main() {
// Create a server
s := sse.NewServer()
go func() {
// Create our first message
m := sse.Message{}
m.AppendText("Hello world")
// Every second, publish the message
for range time.Tick(time.Second) {
_ = s.Publish(&m)
}
}()
// Setup CORS
uiCorsRouter := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowCredentials: true,
}).Handler(s)
// Start the server
if err := http.ListenAndServe(":8000", uiCorsRouter); err != nil {
log.Fatalln(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment