Context is package in the standard library, used for:
- Canceling goroutines
- controlling timeouts (e. g. for API calling)
- passing metadata
ctx := context.Background() // basically an empty struct
ctxWithTimeout, cancel := context.WithTimeout(ctx, 2*time.Second) // timing out after 2 sec
defer cancel()
We can then have this as deadline in the code, waiting for ctxWithTimeout.Done()