Context Cancelable
ID |
go.context_cancelable |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Go |
Tags |
reliability, resource-leak |
Description
Reports a cancelable context.Context created with context.WithCancel, context.WithTimeout
or context.WithDeadline whose returned cancel function is discarded or never invoked.
Rationale
These constructors return a CancelFunc that must be called to release the resources the context
holds. Dropping it (assigning to _) or never calling it leaks a goroutine and a timer until the
parent context is done — a slow resource leak that the Go vet lostcancel analysis also flags.
The idiomatic fix is to defer cancel() immediately after creating the context.
// Bad
ctx, _ := context.WithCancel(parent) // FLAW — cancel discarded
ctx, cancel := context.WithTimeout(parent, d) // FLAW — cancel never called
// Good
ctx, cancel := context.WithCancel(parent) // OK
defer cancel()
Remediation
Keep the cancel function and call it on every path — typically defer cancel() right after
creating the context.