context.Background
- Go course
- Intermediate
- Lesson 29/80
- 4 min
Learn the context package basics and Background.
The context package
context.Context carries a job's cancellation signal, deadline and request-scoped values across functions and goroutines. Every chain has a root:
ctx := context.Background() // main, init, tests
ctx := context.TODO() // when it's not yet clear which ctx to useRule: the context is the function's first parameter, named ctx; it isn't stored in a struct field.
Done and Err
Every context offers two core methods: Done(), a channel that closes on cancellation, and Err(), which returns the reason (context.Canceled or context.DeadlineExceeded). Background is never cancelled; its Done() returns nil.
select {
case <-ctx.Done():
return ctx.Err()
case v := <-sonuc:
return v
}Practice Root context
Create ctx := context.Background(). Print ctx.Err() and ctx.Done() == nil on one line.
Starter code
package main
import (
"context"
"fmt"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"context"
"fmt"
)
func main() {
ctx := context.Background()
fmt.Println(ctx.Err(), ctx.Done() == nil)
}Expected output
<nil> true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which context is used in an HTTP handler?
- context.TODO()
- nil
- r.Context() Correct answer
- context.Background()
Explanation: The request's context is cancelled when the client closes the connection; using Background loses that signal.
2 Root context
ctx := context.____()
isle(ctx)
ctx := context.Background()
isle(ctx)
Explanation: context.Background is the empty, never-cancelled root context.
3 context concepts
| Term | Meaning |
|---|---|
Background() |
Root |
TODO() |
Temporary placeholder |
Done() |
Cancellation channel |
Err() |
Cancellation reason |