title: context - WithDeadline() vs WithTimeout()
body: <p>Below code:</p>
  <pre><code>// Sample program to show how to use the WithDeadline function
  // of the Context package.
  package main
  
  import (
      &quot;context&quot;
      &quot;fmt&quot;
      &quot;time&quot;
  )
  
  type data struct {
      UserID string
  }
  
  func main() {
  
      // Set a duration.
      // duration := 150 * time.Millisecond
      duration := time.Now().Add(3 * time.Second)
  
      // Create a context that is both manually cancellable and will signal
      // a cancel at the specified duration.
      ctx, cancel := context.WithDeadline(context.Background(), duration)
      defer cancel()
  
      // Create a channel to received a signal that work is done.
      ch := make(chan data, 1)
      // Ask the goroutine to do some work for us.
      go func() {
  
          // Simulate work.
          time.Sleep(50 * time.Millisecond)
  
          // Report the work is done.
          ch &lt;- data{&quot;123&quot;}
      }()
  
      // Wait for the work to finish. If it takes too long move on.
      select {
      case d := &lt;-ch:
          fmt.Println(&quot;work complete&quot;, d)
      case &lt;-ctx.Done():
          fmt.Println(&quot;work cancelled&quot;)
      }
  }
  </code></pre>
  <hr />
  <p>is using <code>WithDeadline</code> for sending timer'd <code>cancel()</code>. This can be done using:</p>
  <pre><code>duration := 150 * time.Millisecond
  
  // Create a context that is both manually cancellable and will signal
  // a cancel at the specified duration.
  ctx, cancel := context.WithTimeout(context.Background(), duration)
  </code></pre>
  <hr />
  <p>Internally, <code>context.WithTimeout</code> calls the <code>context.WithDeadline</code> function and generates the deadline by adding timeout to the current time.</p>
  <p>How <code>context.WithTimeout()</code> different from <code>context.WithDeadline()</code></p>