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
Syntax
func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
Parameters
| Parameter | Description |
|---|---|
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
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.
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.
Related
time.Duration, Parse and Format· Represent durations, measure elapsed time, and parse or format times with Go's reference layout (2006-01-02 15:04:05).sync.WaitGroup· Wait for a group of goroutines to finish; WaitGroup.Go (Go 1.25+) starts a goroutine and tracks it in one call.- Go Context · tutorial