htmgo/examples/chat/ws/handler.go

78 lines
1.6 KiB
Go
Raw Normal View History

package ws
import (
2024-10-02 03:26:03 +00:00
"fmt"
2024-10-01 03:08:52 +00:00
"github.com/go-chi/chi/v5"
"github.com/maddalax/htmgo/framework/h"
"github.com/maddalax/htmgo/framework/service"
2024-10-01 17:09:22 +00:00
"log/slog"
"net/http"
2024-10-02 03:26:03 +00:00
"time"
)
func Handle() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
cc := r.Context().Value(h.RequestContextKey).(*h.RequestContext)
2024-10-01 03:08:52 +00:00
2024-10-01 17:09:22 +00:00
sessionCookie, _ := r.Cookie("session_id")
2024-10-01 03:08:52 +00:00
2024-10-01 17:09:22 +00:00
if sessionCookie == nil {
slog.Error("session cookie not found")
return
}
2024-10-01 03:08:52 +00:00
locator := cc.ServiceLocator()
manager := service.Get[SocketManager](locator)
2024-10-01 03:08:52 +00:00
sessionId := sessionCookie.Value
roomId := chi.URLParam(r, "id")
if roomId == "" {
2024-10-01 17:09:22 +00:00
slog.Error("invalid room", slog.String("room_id", roomId))
2024-10-02 03:26:03 +00:00
manager.CloseWithError(sessionId, 1008, "invalid room")
2024-10-01 03:08:52 +00:00
return
}
2024-10-02 03:26:03 +00:00
done := make(chan CloseEvent, 50)
flush := make(chan bool, 50)
manager.Add(roomId, sessionId, w, done, flush)
defer func() {
2024-10-01 03:08:52 +00:00
manager.Disconnect(sessionId)
}()
2024-10-02 03:26:03 +00:00
// Set the necessary headers
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Access-Control-Allow-Origin", "*") // Optional for CORS
// Flush the headers immediately
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
return
}
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
for {
2024-10-02 03:26:03 +00:00
select {
case <-ticker.C:
manager.Ping(sessionId)
case <-flush:
if flusher != nil {
flusher.Flush()
}
case <-done: // Client closed the connection
fmt.Println("Client disconnected")
return
}
}
}
}