diff --git a/main.go b/main.go index 66d57fe..7420502 100644 --- a/main.go +++ b/main.go @@ -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)) } diff --git a/static/index.html b/static/index.html index e223af2..d9c8890 100644 --- a/static/index.html +++ b/static/index.html @@ -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>