Go 1.27 reference · Errors, Context and Time

Go context.WithTimeout and WithCancel Function

Derive a context that is cancelled after a timeout or on demand, to stop work and outbound calls that take too long.

Go 1.27

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

Parameters

ParameterDescription
parent Usually the request's context, or context.Background().
cancel() Always defer it to release resources.
ctx.Done() / ctx.Err() Channel closed on cancellation / why it ended.

Examples

Example 1
package main

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

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	defer cancel()
	select {
	case <-time.After(200 * time.Millisecond):
		fmt.Println("work finished")
	case <-ctx.Done():
		fmt.Println("gave up:", ctx.Err())
	}
}

Output

gave up: context deadline exceeded

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

Cancel with a cause
package main

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

func main() {
	ctx, cancel := context.WithCancelCause(context.Background())
	cancel(errors.New("user logged out"))
	<-ctx.Done()
	fmt.Println(ctx.Err(), "|", context.Cause(ctx))
}

Output

context canceled | user logged out

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

Was this page helpful?