Skip to content

Instantly share code, notes, and snippets.

@blinkinglight
Last active August 26, 2024 17:51
Show Gist options
  • Save blinkinglight/b0a98fd74a4bef9cf5196780435ebdad to your computer and use it in GitHub Desktop.
Save blinkinglight/b0a98fd74a4bef9cf5196780435ebdad to your computer and use it in GitHub Desktop.
htmx.org sse
package main
import (
"fmt"
"net/http"
"time"
"github.com/r3labs/sse/v2"
)
func main() {
server := sse.New()
_ = server.CreateStream("chat")
_ = server.CreateStream("messages")
_ = server.CreateStream("notifications")
mux := http.NewServeMux()
mux.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
go func() {
// Received Browser Disconnection
<-r.Context().Done()
println("The client is disconnected here")
return
}()
server.ServeHTTP(w, r)
})
mux.HandleFunc("/chatroom", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<div>Hello from chat room</div>`))
})
mux.HandleFunc("/index", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`
<html>
<head>
<script src="https://unpkg.com/[email protected]/dist/htmx.js" integrity="sha384-yZq+5izaUBKcRgFbxgkRYwpHhHHCpp5nseXp0MEQ1A4MTWVMnqkmcuFez8x5qfxr" crossorigin="anonymous"></script>
<script src="https://unpkg.com/[email protected]/sse.js"></script>
</head>
<body hx-ext="sse" sse-connect="/events?stream=messages">
<div >
<div sse-swap="hello-post-1">one</div>
</div>
<div>
<div sse-swap="hello-post-1">one</div>
</div>
<div>
<div sse-swap="hello-post-1">one</div>
</div>
<div hx-ext="sse" sse-connect="/events?stream=notifications">
<div sse-swap="hello-post-2">one</div>
</div>
<div>
<div hx-ext="sse" sse-connect="/events?stream=chat">
<div hx-get="/chatroom" hx-trigger="sse:chatter">
chat body reloaded
</div>
</div>
</div>
</body></html>
`))
})
go func() {
i := 0
for {
i++
time.Sleep(1 * time.Second)
server.TryPublish("messages", &sse.Event{
ID: []byte(fmt.Sprintf("%d", i)),
Event: []byte("hello-post-1"),
Data: []byte(`<div>Hello from sse ` + fmt.Sprintf("%d", i) + `</div>`),
})
server.TryPublish("notifications", &sse.Event{
ID: []byte(fmt.Sprintf("%d", i)),
Event: []byte("hello-post-2"),
Data: []byte(`<div>Hello from post 2 sse ` + fmt.Sprintf("%d", i) + `</div>`),
})
server.TryPublish("chat", &sse.Event{
ID: []byte(fmt.Sprintf("%d", i)),
Event: []byte("chatter"),
Data: []byte(`<div></div>`),
})
}
}()
http.ListenAndServe(":9999", mux)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment