Context package

at Helsinki Gophers meetup

18 January 2017

Timo Savola

CTO, Ninchat

History

Three jobs

Characteristics

Deadlines

Cancellation

Values

Building blocks

func Foo(ctx Context, ...)

Example: Top level

func main() {
    ctx := context.Background() // No timeout, cancellation, or values

    app(ctx)
}

Example: Reacting to events

func app(ctx Context) {
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()

    go waitForSignalAndInvoke(os.Interrupt, cancel)

    doStuff(ctx)
}

func waitForSignalAndInvoke(number os.Signal, cancel context.CancelFunc) {
    c := make(chan os.Signal)
    signal.Notify(c, number)
    <-c
    cancel()
}

Example: API call with a deadline

func doStuff(ctx Context) (err error) {
    ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
    defer cancel()

    result, err := api.PerformOperation(ctx, 10, 20)
    if err != nil {
        return
    }

    fmt.Println(result)
    return
}

Example: Implementation of a blocking API

func PerformOperation(ctx Context, x, y int) (result int, err error) {
    performance := startPerforming(x, y)

    select {
    case result, _ = <-performance.resultChannel:
        return

    case <-ctx.Done(): // Timed out or cancelled?
        err = ctx.Err()
        performance.abort()
        return
    }
}

API implementation support

Supported by net package

since 1.7:

Dialer.DialContext(ctx Context, net, addr string) (Conn, error)

since 1.8:

Resolver.LookupAddr(ctx Context, addr string) (names []string, err error)
Resolver.LookupCNAME(ctx Context, host string) (cname string, err error)
Resolver.LookupHost(ctx Context, host string) (addrs []string, err error)
...

Supported by net/http package

since 1.7:

Request.WithContext(ctx Context) *Request
Request.Context() Context
ServerContextKey
LocalAddrContextKey

since 1.8:

Server.Shutdown(ctx Context) error

Supported by os/exec package

since 1.7:

CommandContext(ctx Context, name string, arg ...string) *Cmd

Supported by database/sql package

since 1.8:

DB.QueryContext(ctx Context, query string, args ...interface{}) (*Rows, error)
...

Thoughts

Thank you

Timo Savola

CTO, Ninchat