From 6192b0e6ae971368c2bc1a9c8359a922a12103ae Mon Sep 17 00:00:00 2001 From: toad Date: Tue, 7 Jan 2025 18:08:42 +0800 Subject: [PATCH] fix: `OnConnected` is called with a copied context. --- server/context.go | 17 +++++++++++++++++ server/serverimpl.go | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 server/context.go diff --git a/server/context.go b/server/context.go new file mode 100644 index 00000000..9e4a2aa3 --- /dev/null +++ b/server/context.go @@ -0,0 +1,17 @@ +package server + +import ( + "context" + "time" +) + +// Detach returns a context that keeps all the values of its parent context +// but detaches from the cancellation and error handling. +func Detach(ctx context.Context) context.Context { return detachedContext{ctx} } + +type detachedContext struct{ parent context.Context } + +func (v detachedContext) Deadline() (time.Time, bool) { return time.Time{}, false } +func (v detachedContext) Done() <-chan struct{} { return nil } +func (v detachedContext) Err() error { return nil } +func (v detachedContext) Value(key interface{}) interface{} { return v.parent.Value(key) } diff --git a/server/serverimpl.go b/server/serverimpl.go index 815c0528..902c2e6e 100644 --- a/server/serverimpl.go +++ b/server/serverimpl.go @@ -201,7 +201,7 @@ func (s *server) httpHandler(w http.ResponseWriter, req *http.Request) { // Return from this func to reduce memory usage. // Handle the connection on a separate goroutine. - go s.handleWSConnection(req.Context(), conn, connectionCallbacks) + go s.handleWSConnection(Detach(req.Context()), conn, connectionCallbacks) } func (s *server) handleWSConnection(reqCtx context.Context, wsConn *websocket.Conn, connectionCallbacks serverTypes.ConnectionCallbacks) {