What Is the Difference Between context.WithTimeout and context.WithDeadline

Use WithTimeout for a duration and WithDeadline for a specific time to cancel Go contexts.

Use context.WithTimeout to cancel a context after a fixed duration, and context.WithDeadline to cancel it at a specific point in time.

// Cancel after 5 seconds
ctx, cancel := context.WithTimeout(parent, 5*time.Second)
defer cancel()

// Cancel at a specific time
deadline := time.Now().Add(5 * time.Second)
ctx, cancel := context.WithDeadline(parent, deadline)
defer cancel()