htmgo/examples/chat/ws/handler.go

69 lines
1.5 KiB
Go
Raw Normal View History

package ws
import (
"context"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
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"
)
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
c, err := websocket.Accept(w, r, nil)
2024-10-01 03:08:52 +00:00
2024-10-01 17:42:01 +00:00
// 2 mb
c.SetReadLimit(2 * 1024 * 1024)
2024-10-01 03:08:52 +00:00
if err != nil {
return
}
2024-10-01 17:09:22 +00:00
if sessionCookie == nil {
slog.Error("session cookie not found")
c.Close(websocket.StatusPolicyViolation, "no session")
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))
manager.CloseWithError(sessionId, websocket.StatusPolicyViolation, "invalid room")
2024-10-01 03:08:52 +00:00
return
}
manager.Add(roomId, sessionId, c)
defer func() {
2024-10-01 03:08:52 +00:00
manager.Disconnect(sessionId)
}()
for {
var v map[string]any
err = wsjson.Read(context.Background(), c, &v)
if err != nil {
2024-10-01 17:09:22 +00:00
slog.Error("failed to read message", slog.String("room_id", roomId))
manager.CloseWithError(sessionId, websocket.StatusInternalError, "failed to read message")
return
}
if v != nil {
2024-10-01 03:08:52 +00:00
manager.OnMessage(sessionId, v)
}
}
}
}