Pass contexts to I/O functions

MEDIUM1.2.1
When to apply When writing Go functions that do I/O.

Rule

Pass context.Context as the first parameter of every function that does I/O. See the example and the style guide.

Evidence

I/O functions take a context first.

Example: HTTP handlers

Use r.Context() in HTTP handlers. Prefer errors.Is in HTTP handlers too.

Example: background work

Derive a context with context.WithTimeout or context.WithCancel for background work.