Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion sdk/api/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -339,12 +339,13 @@ func (h *BaseAPIHandler) GetContextWithCancel(handler interfaces.APIHandler, c *
}
}
newCtx, cancel := context.WithCancel(parentCtx)
cancelCtx := newCtx
if requestCtx != nil && requestCtx != parentCtx {
go func() {
select {
case <-requestCtx.Done():
cancel()
case <-newCtx.Done():
case <-cancelCtx.Done():
}
}()
}
Comment on lines +342 to 351
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

While this change correctly fixes the data race, a more idiomatic Go approach is to pass newCtx as an argument to the goroutine. This makes the variable capture explicit and is a safer pattern for concurrent code, as it avoids potential confusion with closure variable capturing.

	if requestCtx != nil && requestCtx != parentCtx {
		go func(ctxToWatch context.Context) {
			select {
			case <-requestCtx.Done():
				cancel()
			case <-ctxToWatch.Done():
			}
		}(newCtx)
	}
References
  1. To prevent data races when using variables inside a goroutine, it's a best practice to pass them as arguments to the goroutine's function. This creates a copy of the variable for the goroutine, ensuring it doesn't get affected by modifications in the parent goroutine.

Expand Down
Loading