contextpolicy
Checks context placement, storage, nil use, and test ownership.
What it detects
Reports context.Context parameters that are not first, contexts stored in
structs, and calls that pass a definitely nil context. In supported test code,
it also prefers t.Context() or b.Context() over context.Background().
Checks
| Check | What it detects |
|---|---|
context-first |
Reports context.Context parameters that are not first. |
context-storage |
Reports context.Context values stored in structs. |
test-context* |
Reports tests that use context.Background instead of the testing handle’s context. |
nil-context |
Reports definitely nil context.Context arguments. |
* Opt-in; requires explicit selection.
Why this is flagged
Keeping context.Context as the first parameter makes cancellation and
deadlines easy to pass through a call chain. Storing a context or passing nil
can give it the wrong lifetime or cause failures far from the call site.
Further reading: Package context, Contexts and structs.
How to fix it
Accept the context as the function’s first parameter and pass it directly to the work that needs it. Do not store it in a struct or pass nil; use an appropriate real context, such as the test’s context in test code.
Examples
Flagged code
Context parameter order
// gohawk: context.Context must be first parameterfunc LoadUser(id string, ctx context.Context) error { return nil}Context stored in a struct
type Request struct { // gohawk: do not store context.Context in a struct Context context.Context}Nil context argument
func acceptContext(context.Context) {}
func loadWithoutContext() { // gohawk: do not pass nil context.Context acceptContext(nil)}Accepted code
func LoadUserCorrectly(ctx context.Context, id string) error { return nil}Options
| Knob | Default | Effect |
|---|---|---|
prefer-test-context |
true |
Prefer t.Context or b.Context over context.Background in tests. |