How to Use context.WithTimeout in Go

Create a context with a deadline using context.WithTimeout to automatically cancel operations after a set duration.

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
}
  1. Import the context and time packages.
  2. Call context.WithTimeout with a parent context and a time.Duration to get a new context and a cancel function.
  3. Defer the cancel function immediately to ensure resources are released.
  4. Pass the new context to functions that support it.
  5. Check for context.DeadlineExceeded errors to handle the timeout case.