TExcelTAD
Home › Go › Go Context

Go Context

In a server, one incoming request often starts many goroutines: database queries, calls to other services, background calculations. If the client disconnects or a deadline passes, all that work should stop. The context package provides a standard way to carry cancellation signals, deadlines and request-scoped values across function calls and goroutines.

The Context interface

go
type Context interface {
	Deadline() (deadline time.Time, ok bool)
	Done() <-chan struct{} // closed when the context is cancelled or times out
	Err() error            // why: context.Canceled or context.DeadlineExceeded
	Value(key any) any     // request-scoped data
}

Contexts form a tree. You start from a root and derive children; cancelling a parent cancels all of its children.

Function Creates a context that…
context.Background() is the root: never cancelled, no values
context.TODO() is a placeholder when you are not sure which context to use yet
context.WithCancel(parent) is cancelled when you call the returned cancel function
context.WithTimeout(parent, d) is cancelled automatically after duration d
context.WithDeadline(parent, t) is cancelled at time t
context.WithValue(parent, key, val) carries a key–value pair

By convention, a context is the first parameter of a function and is named ctx:

go
func FetchUser(ctx context.Context, id int) (*User, error)

Cancelling work

The worker below checks ctx.Done() in a select. When main calls cancel(), the Done channel is closed, and the worker returns. Using an unbuffered ticks channel makes the number of completed steps deterministic: the worker can only advance when main receives.

go · try it yourself
package main

import (
	"context"
	"fmt"
)

func counter(ctx context.Context, ticks chan<- int, stopped chan<- error) {
	for i := 1; ; i++ {
		select {
		case <-ctx.Done():
			stopped <- ctx.Err()
			return
		case ticks <- i:
		}
	}
}

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	ticks := make(chan int)
	stopped := make(chan error)

	go counter(ctx, ticks, stopped)

	for range 3 {
		fmt.Println("tick", <-ticks)
	}
	cancel() // tell the worker to stop
	fmt.Println("worker stopped:", <-stopped)
}
tick 1
tick 2
tick 3
worker stopped: context canceled

Tip: Always call the cancel function returned by WithCancel, WithTimeout and WithDeadline — typically with defer cancel() right after creating the context. Otherwise resources stay allocated until the parent is cancelled.

Timeouts

WithTimeout cancels the context automatically. The slow operation below would take two seconds, but the context only allows 50 ms, so it gives up with context.DeadlineExceeded.

go · try it yourself
package main

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

// slowQuery pretends to query a database that takes `cost` to answer.
func slowQuery(ctx context.Context, cost time.Duration) (string, error) {
	select {
	case <-time.After(cost):
		return "42 rows", nil
	case <-ctx.Done():
		return "", ctx.Err()
	}
}

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

	res, err := slowQuery(ctx, 2*time.Second)
	fmt.Printf("result=%q err=%v\n", res, err)
	fmt.Println("deadline exceeded?", errors.Is(err, context.DeadlineExceeded))

	quick, cancel2 := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel2()
	res, err = slowQuery(quick, 5*time.Millisecond)
	fmt.Printf("result=%q err=%v\n", res, err)
}
result="" err=context deadline exceeded
deadline exceeded? true
result="42 rows" err=<nil>

Cancellation flows down the tree

Cancelling a parent closes the Done channel of every context derived from it. Cancelling a child does not affect the parent.

go · try it yourself
package main

import (
	"context"
	"fmt"
)

func status(name string, ctx context.Context) {
	select {
	case <-ctx.Done():
		fmt.Printf("%-6s cancelled (%v)\n", name, ctx.Err())
	default:
		fmt.Printf("%-6s active\n", name)
	}
}

func main() {
	parent, cancelParent := context.WithCancel(context.Background())
	child, cancelChild := context.WithCancel(parent)
	sibling, cancelSibling := context.WithCancel(parent)
	defer cancelSibling()

	cancelChild()
	fmt.Println("after cancelling child:")
	status("parent", parent)
	status("child", child)
	status("sibling", sibling)

	cancelParent()
	fmt.Println("after cancelling parent:")
	status("parent", parent)
	status("sibling", sibling)
}
after cancelling child:
parent active
child  cancelled (context canceled)
sibling active
after cancelling parent:
parent cancelled (context canceled)
sibling cancelled (context canceled)

Request-scoped values

WithValue attaches data such as a request ID or the authenticated user. Use an unexported key type to avoid collisions between packages, and keep values to request metadata — not optional function parameters.

go · try it yourself
package main

import (
	"context"
	"fmt"
)

type ctxKey string

const requestIDKey ctxKey = "requestID"

func logf(ctx context.Context, msg string) {
	id, _ := ctx.Value(requestIDKey).(string)
	if id == "" {
		id = "-"
	}
	fmt.Printf("[req %s] %s\n", id, msg)
}

func handle(ctx context.Context) {
	logf(ctx, "loading user")
	logf(ctx, "rendering page")
}

func main() {
	ctx := context.WithValue(context.Background(), requestIDKey, "a1b2")
	handle(ctx)
	logf(context.Background(), "no request")
}
[req a1b2] loading user
[req a1b2] rendering page
[req -] no request

Context rules of thumb

  • Pass ctx explicitly as the first parameter; don't store it in a struct.
  • Never pass a nil context — use context.TODO() if unsure.
  • Functions that can block (network, database, long loops) should accept a ctx and return when ctx.Done() is closed.
  • In HTTP servers, r.Context() is cancelled automatically when the client goes away.

Test yourself

What happens to ctx.Done() when a context is cancelled?

  1. It receives one value
  2. The channel is closed
  3. It becomes nil
  4. It panics

What does ctx.Err() return after a WithTimeout deadline passes?

  1. nil
  2. context.Canceled
  3. context.DeadlineExceeded
  4. io.EOF

If you cancel a child context, what happens to its parent?

  1. It is cancelled too
  2. Nothing
  3. It panics
  4. All siblings are cancelled