Created
April 5, 2024 10:17
-
-
Save arturo-source/98e6994fa64867d53b10f03e74b6d2ff to your computer and use it in GitHub Desktop.
Server Side Event (sse) example with Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"time" | |
) | |
var html = []byte(` | |
<!DOCTYPE html> | |
<html lang="en"> | |
<body> | |
<button>Close the connection</button> | |
<ul> | |
</ul> | |
<script> | |
const button = document.querySelector('button'); | |
const evtSource = new EventSource('/sse'); | |
console.log(evtSource.withCredentials); | |
console.log(evtSource.readyState); | |
console.log(evtSource.url); | |
const eventList = document.querySelector('ul'); | |
evtSource.onopen = function() { | |
console.log("Connection to server opened."); | |
}; | |
evtSource.onmessage = function(e) { | |
const newElement = document.createElement("li"); | |
newElement.textContent = e.data; | |
eventList.appendChild(newElement); | |
}; | |
evtSource.onerror = function() { | |
console.log("EventSource failed."); | |
}; | |
button.onclick = function() { | |
console.log('Connection closed'); | |
evtSource.close(); | |
}; | |
</script> | |
</body> | |
</html> | |
`) | |
func main() { | |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
w.Write(html) | |
}) | |
http.HandleFunc("/sse", func(w http.ResponseWriter, r *http.Request) { | |
fmt.Println("start sse", r.RemoteAddr) | |
w.Header().Set("Content-Type", "text/event-stream") | |
w.Header().Set("Cache-Control", "no-cache") | |
w.Header().Set("Connection", "keep-alive") | |
ticker := time.NewTicker(time.Second) | |
infLoop: | |
for { | |
select { | |
case t := <-ticker.C: | |
fmt.Fprint(w, "data:", t, "\n\n") | |
w.(http.Flusher).Flush() | |
case <-r.Context().Done(): | |
break infLoop | |
} | |
} | |
fmt.Println("end sse", r.RemoteAddr) | |
}) | |
fmt.Println("listen to http://localhost:9000/") | |
http.ListenAndServe(":9000", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment