Table of Contents

context.Context

What is it?

`context.Context` is a standard way to carry:

across API boundaries and between goroutines.

What is it used for?

Core functions

Example: timeout for work

package main
 
import (
    "context"
    "time"
)
 
func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()
 
    _ = ctx // pass ctx into HTTP/DB/RPC calls
}

Example: cancellation (stop goroutine)

package main
 
import (
    "context"
    "time"
)
 
func worker(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            return
        default:
            time.Sleep(10 * time.Millisecond)
        }
    }
}
 
func main() {
    ctx, cancel := context.WithCancel(context.Background())
    go worker(ctx)
 
    time.Sleep(50 * time.Millisecond)
    cancel()
    time.Sleep(20 * time.Millisecond)
}

Notes / pitfalls

Hard words (English)