Context package
at Helsinki Gophers meetup
18 January 2017
Timo Savola
CTO, Ninchat
Timo Savola
CTO, Ninchat
golang.org/x/net/context
package released in 2014context
package in standard library since Go 1.7func Foo(ctx Context, ...)
func main() { ctx := context.Background() // No timeout, cancellation, or values app(ctx) }
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() }
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 }
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 } }
Context.Done()
channel will be closed on deadline or cancellationContext.Deadline()
value may be used with readers/writers, but it doesn't respect cancellationsince 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) ...
since 1.7:
Request.WithContext(ctx Context) *Request Request.Context() Context ServerContextKey LocalAddrContextKey
since 1.8:
Server.Shutdown(ctx Context) error
since 1.7:
CommandContext(ctx Context, name string, arg ...string) *Cmd
since 1.8:
DB.QueryContext(ctx Context, query string, args ...interface{}) (*Rows, error) ...