Created
February 21, 2024 19:48
-
-
Save blinkinglight/da8fde83640f2a743c2bfe00f74903f0 to your computer and use it in GitHub Desktop.
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 ( | |
"log" | |
"net/http" | |
"time" | |
"github.com/go-chi/chi/v5" | |
) | |
func main() { | |
r := chi.NewRouter() | |
q := make(chan string) | |
r.Get("/events", func(w http.ResponseWriter, r *http.Request) { | |
flusher, ok := w.(http.Flusher) | |
if !ok { | |
http.Error(w, "SSE not supported", http.StatusInternalServerError) | |
return | |
} | |
w.Header().Set("Content-Type", "text/event-stream") | |
w.Header().Set("Cache-Control", "no-cache") | |
w.Header().Set("Connection", "keep-alive") | |
for { | |
select { | |
case <-r.Context().Done(): | |
return | |
case m := <-q: | |
w.Write([]byte("event: clock" + "\n")) | |
w.Write([]byte("data: " + m + " " + time.Now().Format(time.RFC3339) + "\n\n")) | |
flusher.Flush() | |
} | |
} | |
}) | |
r.Get("/send", func(w http.ResponseWriter, r *http.Request) { | |
q <- "Hello, world!" | |
w.Write([]byte("Sent")) | |
}) | |
r.Get("/", func(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte(` | |
<!DOCTYPE html> | |
<html> | |
<head> | |
<script src="https://unpkg.com/[email protected]"></script> | |
<script src="https://unpkg.com/htmx.org/dist/ext/sse.js"></script> | |
</head> | |
<body> | |
<div hx-ext="sse" sse-connect="http://localhost:3000/events" sse-swap="clock"> | |
<div id="clock"></div> | |
</div> | |
</body> | |
</html> | |
`)) | |
}) | |
log.Printf("Starting...") | |
http.ListenAndServe(":3000", r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment