2024-09-30 21:05:06 +00:00
|
|
|
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"
|
2024-09-30 21:05:06 +00:00
|
|
|
"github.com/maddalax/htmgo/framework/h"
|
|
|
|
|
"github.com/maddalax/htmgo/framework/service"
|
|
|
|
|
"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
|
|
|
|
|
|
|
|
sessionCookie, err := r.Cookie("session_id")
|
|
|
|
|
|
|
|
|
|
cookies := r.Cookies()
|
|
|
|
|
|
|
|
|
|
println(cookies)
|
|
|
|
|
// no session
|
|
|
|
|
if err != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
c, err := websocket.Accept(w, r, nil)
|
|
|
|
|
|
2024-09-30 21:05:06 +00:00
|
|
|
locator := cc.ServiceLocator()
|
|
|
|
|
manager := service.Get[SocketManager](locator)
|
|
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-01 03:08:52 +00:00
|
|
|
sessionId := sessionCookie.Value
|
|
|
|
|
|
|
|
|
|
roomId := chi.URLParam(r, "id")
|
|
|
|
|
|
|
|
|
|
if roomId == "" {
|
|
|
|
|
manager.CloseWithError(sessionId, "invalid room")
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
manager.Add(roomId, sessionId, c)
|
2024-09-30 21:05:06 +00:00
|
|
|
|
|
|
|
|
defer func() {
|
2024-10-01 03:08:52 +00:00
|
|
|
manager.Disconnect(sessionId)
|
2024-09-30 21:05:06 +00:00
|
|
|
}()
|
|
|
|
|
|
|
|
|
|
for {
|
|
|
|
|
var v map[string]any
|
|
|
|
|
err = wsjson.Read(context.Background(), c, &v)
|
|
|
|
|
if err != nil {
|
2024-10-01 03:08:52 +00:00
|
|
|
manager.CloseWithError(sessionId, "failed to read message")
|
2024-09-30 21:05:06 +00:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if v != nil {
|
2024-10-01 03:08:52 +00:00
|
|
|
manager.OnMessage(sessionId, v)
|
2024-09-30 21:05:06 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|