Go Foundations·Clarity, then concurrency

Context and timeouts

Use context to cancel work, time out HTTP requests and avoid leaking goroutines.

Beginner 14 min read Lesson 5 of 300 Challenge included
What you will be able to do
  • Pass context.Context to operations that can be cancelled or timed out.
  • Always call the cancel function returned by WithTimeout or WithCancel.
  • Put a timeout on HTTP requests using http.NewRequestWithContext.
  • Never start a goroutine without a way for it to stop.

In plain English

A goroutine is a lightweight function that runs at the same time as other goroutines, and if it never finishes it becomes a leak that holds memory. A context.Context carries cancellation and deadline information through a call, so long work can stop when it is no longer needed. context.WithTimeout returns a context that cancels itself after a duration, and you call the returned cancel function to clean it up early. Passing a context into an HTTP request lets a slow server or client be cut off instead of waiting forever.

Step by step

  1. 1Start with context.Background and wrap it with WithTimeout.
  2. 2Pass the context into the function that does the work.
  3. 3Call the cancel function with defer so the timer is cleaned up.
  4. 4Attach the context to HTTP requests with http.NewRequestWithContext.
fetch.goGo
package main

import (
    "context"
    "fmt"
    "net/http"
    "time"
)

func fetch(ctx context.Context, url string) error {
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
    if err != nil {
        return err
    }

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    fmt.Println(url, resp.StatusCode)
    return nil
}

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()

    if err := fetch(ctx, "https://example.com"); err != nil {
        fmt.Println(err)
    }
}

Common mistakes

  • Forgetting to call cancel leaks the timer and the context until it eventually fires.
  • Starting a goroutine that blocks on a channel with no sender leaks the goroutine forever.
  • Using an HTTP request without a context lets a slow endpoint hang your program.
  • Creating a context and discarding the cancel function is wrong, because that function is how you stop early.
Your turn

Apply a timeout

Medium

Write a function run that creates a context with a 3-second timeout, calls work(ctx), and always calls the cancel function.

GO · starter
func run() {
    ctx := context.Background()
    work(ctx)
}
Check your understanding before moving on.
Knowledge checkQuestion 1

Why pass a context.Context to a long-running operation?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 5 of 300 · 0% of course