crowdsecurity/crowdsec · error
context must be non-nil
Error message
context must be non-nil
What it means
ApiClient.Do requires a context to attach to the outgoing HTTP request via req.WithContext(ctx). A nil context would make cancellation, deadlines and trace propagation impossible, so the client rejects it up front instead of failing obscurely inside net/http.
Source
Thrown at pkg/apiclient/client_http.go:76
req, err := http.NewRequestWithContext(ctx, method, u.String(), buf)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
if compressedBody {
req.Header.Set("Content-Encoding", "gzip")
}
}
return req, nil
}
func (c *ApiClient) Do(ctx context.Context, req *http.Request, v any) (*Response, error) {
if ctx == nil {
return nil, errors.New("context must be non-nil")
}
req = req.WithContext(ctx)
// Check rate limit
if c.UserAgent != "" {
req.Header.Add("User-Agent", c.UserAgent)
}
log.Debugf("[URL] %s %s", req.Method, req.URL)
resp, err := c.client.Do(req)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {View on GitHub (pinned to 909b515798)
Solutions
- Pass a valid context: use context.Background() or context.TODO() when no request-scoped context exists.
- Pass the ctx received from an HTTP handler, command, or parent function instead of a stored nil field.
- Add a nil-check/default at the call site wrapper before invoking Do.
Example fix
// before var ctx context.Context resp, err := client.Do(ctx, req, &result) // after ctx := context.Background() resp, err := client.Do(ctx, req, &result)
Defensive patterns
Strategy: validation
Validate before calling
if ctx == nil {
ctx = context.Background()
}
resp, err := client.Do(ctx, req, &result) Type guard
func validCtx(ctx context.Context) context.Context {
if ctx == nil {
return context.Background()
}
return ctx
} Try / catch
resp, err := client.Do(ctx, req, &out)
if err != nil {
return fmt.Errorf("api call: %w", err)
} Prevention
- Never declare a context.Context without initializing it; always assign context.Background/TODO or a parent ctx.
- Lint for nil-context params in HTTP client wrappers.
- Thread ctx through function signatures instead of storing it in structs.
When it happens
Trigger: Calling Do(ctx, req, v) with a literally nil context.Context value, or with a variable that was declared as context.Context without initialization (zero value of an interface).
Common situations: Older code written before context was pervasive, wrappers that pass through a nil ctx field of a struct, tests that call Do(nil, ...) directly, refactors where a caller dropped ctx argument handling.
Related errors
- while performing request: %w
- path must start with /
- chunk_size must be positive
- invalid HTTP status code
- missing basic auth
AI-assisted analysis of crowdsecurity/crowdsec@909b515798 (2026-09-06).
Data as JSON: /api/errors/f2580be1c5294446.
Report an issue: GitHub.