contextfirst
About 245 words
Ensures context.Context is the first parameter in function signatures.
Category
Architecture
What It Checks
This analyzer detects functions where context.Context is not the first parameter. The reported position counts every parameter name, so in func f(a, b int, ctx context.Context) the context is parameter 3.
Only the standard library's context.Context (or an alias of it) counts. Framework types that are also called Context, such as *gin.Context, are not checked.
Why It Matters
Go convention: context is always first. This:
- Makes code consistent and predictable
- Allows easy visual scanning for context usage
- Follows standard library conventions
Examples
Bad
func GetUser(id string, ctx context.Context) (*User, error) {
// Context buried in parameters
}
func ProcessOrder(order *Order, ctx context.Context, opts ...Option) error {
// Context in the middle
}Good
func GetUser(ctx context.Context, id string) (*User, error) {
// Context is first
}
func ProcessOrder(ctx context.Context, order *Order, opts ...Option) error {
// Context is first, variadic opts are last
}Parameter Order Convention
func DoSomething(
ctx context.Context, // 1. Context first
requiredParam Type, // 2. Required parameters
optionalParam *Type, // 3. Optional parameters
opts ...Option, // 4. Variadic options last
) errorConfiguration
# .golint-sl.yaml
analyzers:
contextfirst: true # enabled by defaultWhen to Disable
- Interface implementations that must match external signatures
- CGO or interop code
analyzers:
contextfirst: falseRelated Analyzers
- contextpropagation - Context propagation
- contextlogger - Context-based logging
