Skip to content

Commit

Permalink
Fix race condition in setting up ws connection
Browse files Browse the repository at this point in the history
  • Loading branch information
ksysoev committed Apr 13, 2024
1 parent 5a76f13 commit dbec7b7
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions channel/channel.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,17 @@ func (c *DefaultChannel) Path() string {

// Handler returns http.Handler for channel
func (c *DefaultChannel) Handler() http.Handler {
var ctx context.Context
return c.setContext(c.wrapMiddleware(c.wsConnectionHandler()))
}

saveCtx := func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx = r.Context()
next.ServeHTTP(w, r)
})
}
// wsConnectionHandler handles the WebSocket connection and sets up the necessary components for communication.
func (c *DefaultChannel) wsConnectionHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()

wsHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ws, err := websocket.Accept(w, r, nil)
ws, err := websocket.Accept(w, r, &websocket.AcceptOptions{
OriginPatterns: []string{"*"},
})

if err != nil {
return
Expand All @@ -61,8 +61,6 @@ func (c *DefaultChannel) Handler() http.Handler {
conn := c.connRegistry.AddConnection(ctx, ws, c.disptacher.Dispatch)
conn.HandleRequests()
})

return c.setContext(c.wrapMiddleware(saveCtx(wsHandler)))
}

// SetContext sets context for channel
Expand Down

0 comments on commit dbec7b7

Please sign in to comment.