Implement Server-Sent Events

This commit is contained in:
Elnu 2023-07-17 09:46:32 -07:00
parent 3fc30c0d3a
commit 3a8179a99a
2 changed files with 32 additions and 0 deletions

29
main.go
View file

@ -5,6 +5,7 @@ import (
"html/template"
"log"
"net/http"
"time"
)
type handler = func(http.ResponseWriter, *http.Request)
@ -27,10 +28,38 @@ func generateClick() handler {
)
}
func generateSseHandler(handler func(http.ResponseWriter, *http.Request)) handler {
return 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")
w.WriteHeader(http.StatusOK)
handler(w, r)
}
}
func generateCounter() handler {
return generateSseHandler(func(w http.ResponseWriter, r *http.Request) {
tick := time.Tick(500 * time.Millisecond)
ctx := r.Context()
outer:
for i := 0; ; i++ {
select {
case <-ctx.Done():
break outer
case <-tick:
fmt.Fprintf(w, "event: count\ndata: %d\n\n", i)
w.(http.Flusher).Flush()
}
}
})
}
func main() {
http.Handle("/", http.FileServer(http.Dir("static")))
http.HandleFunc("/api/click1", generateClick())
http.HandleFunc("/api/click2", generateClick())
http.HandleFunc("/api/click3", generateClick())
http.HandleFunc("/api/counter", generateCounter())
log.Fatal(http.ListenAndServe(":3333", nil))
}

View file

@ -7,6 +7,9 @@
<script src="https://unpkg.com/htmx.org@1.9.3"></script>
</head>
<body>
<div hx-sse="connect:/api/counter">
<div hx-sse="swap:count"></div>
</div>
<button hx-get="/api/click1" hx-swap="innerHTML">Click me!</button>
<br>
<button hx-get="/api/click2" hx-swap="innerHTML">Click me!</button>