generated from ElnuDev/go-project
Implement Server-Sent Events
This commit is contained in:
parent
3fc30c0d3a
commit
3a8179a99a
2 changed files with 32 additions and 0 deletions
29
main.go
29
main.go
|
@ -5,6 +5,7 @@ import (
|
||||||
"html/template"
|
"html/template"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type handler = func(http.ResponseWriter, *http.Request)
|
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() {
|
func main() {
|
||||||
http.Handle("/", http.FileServer(http.Dir("static")))
|
http.Handle("/", http.FileServer(http.Dir("static")))
|
||||||
http.HandleFunc("/api/click1", generateClick())
|
http.HandleFunc("/api/click1", generateClick())
|
||||||
http.HandleFunc("/api/click2", generateClick())
|
http.HandleFunc("/api/click2", generateClick())
|
||||||
http.HandleFunc("/api/click3", generateClick())
|
http.HandleFunc("/api/click3", generateClick())
|
||||||
|
http.HandleFunc("/api/counter", generateCounter())
|
||||||
log.Fatal(http.ListenAndServe(":3333", nil))
|
log.Fatal(http.ListenAndServe(":3333", nil))
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,6 +7,9 @@
|
||||||
<script src="https://unpkg.com/htmx.org@1.9.3"></script>
|
<script src="https://unpkg.com/htmx.org@1.9.3"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<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>
|
<button hx-get="/api/click1" hx-swap="innerHTML">Click me!</button>
|
||||||
<br>
|
<br>
|
||||||
<button hx-get="/api/click2" hx-swap="innerHTML">Click me!</button>
|
<button hx-get="/api/click2" hx-swap="innerHTML">Click me!</button>
|
||||||
|
|
Reference in a new issue