Use context.WithTimeout to create a derived context that cancels automatically after a specified duration.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Use ctx in your function calls
result, err := someFunction(ctx)
if err == context.DeadlineExceeded {
// Handle timeout
}
- Import the
contextandtimepackages. - Call
context.WithTimeoutwith a parent context and atime.Durationto get a new context and a cancel function. - Defer the cancel function immediately to ensure resources are released.
- Pass the new context to functions that support it.
- Check for
context.DeadlineExceedederrors to handle the timeout case.