Go Tutorial · Concurrency · Lesson 25 of 30

Go Context

Cancel work and set deadlines with context.Context.

Why context?

A context.Context carries cancellation, deadlines and request-scoped values through a call chain. When an HTTP client disconnects or a timeout passes, every function using the context can stop early.

  • context.Background() — the root context.
  • context.WithTimeout(ctx, d) / WithDeadline — cancel automatically.
  • context.WithCancel(ctx) — cancel manually.

By convention ctx is the first parameter of functions that do I/O, and you always defer cancel().

Example 1
package main

import (
	"context"
	"fmt"
	"time"
)

func slowQuery(ctx context.Context, d time.Duration) string {
	select {
	case <-time.After(d):
		return "query finished"
	case <-ctx.Done():
		return "query cancelled: " + ctx.Err().Error()
	}
}

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

	fmt.Println(slowQuery(ctx, 20*time.Millisecond))
	fmt.Println(slowQuery(ctx, 500*time.Millisecond))
}

Output

query finished
query cancelled: context deadline exceeded

Run this on your computer — see “Get Started” for setup.

Test yourself

Where does a context.Context parameter conventionally go?

  1. First
  2. Last
  3. Anywhere
  4. In a global variable
Show answer

Answer: First