context

package
v0.0.0-...-15ee061 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 8, 2014 License: BSD-3-Clause Imports: 4 Imported by: 0

Documentation

Overview

Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes.

Incoming requests to a server establish a Context, and outgoing calls to servers should accept a Context. The chain of function calls between must propagate the Context, optionally replacing it with a modified copy created using WithDeadline, WithTimeout, WithCancel, or WithValue.

Functions that require a Context should take it as the first parameter, named ctx:

func DoSomething(ctx context.Context, arg Arg) error {
  // ... use ctx ...
}

Do not pass a nil Context, even if a function permits it. Pass context.TODO if you are unsure about which Context to use.

Future packages will create Contexts from standard request types like *http.Request.

Index

Examples

Constants

This section is empty.

Variables

View Source
var Canceled = errors.New("context canceled")

Canceled is the error returned by Context.Err when the context is canceled.

View Source
var DeadlineExceeded = errors.New("context deadline exceeded")

DeadlineExceeded is the error returned by Context.Err when the context's deadline passes.

Functions

func WithCancel

func WithCancel(parent Context) (ctx Context, cancel CancelFunc)

WithCancel returns a copy of parent with a new Done channel. The returned context's Done channel is closed when the returned cancel function is called or when the parent context's Done channel is closed, whichever happens first.

func WithDeadline

func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)

WithDeadline returns a copy of the parent context with the deadline adjusted to be no later than d. If the parent's deadline is already earlier than d, WithDeadline(parent, d) is semantically equivalent to parent. The returned context's Done channel is closed when the deadline expires, when the returned cancel function is called, or when the parent context's Done channel is closed, whichever happens first.

Cancelling this context releases resources associated with the deadline timer, so code should call cancel as soon as the operations running in this Context complete.

func WithTimeout

func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)

WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).

Cancelling this context releases resources associated with the deadline timer, so code should call cancel as soon as the operations running in this Context complete:

func slowOperationWithTimeout(ctx context.Context) (Result, error) {
  ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
  defer cancel()  // releases resources if slowOperation completes before timeout elapses
  return slowOperation(ctx)
}
Example
package main

import (
	"fmt"
	"time"

	"code.google.com/p/go.net/context"
)

func main() {
	// Pass a context with a timeout to tell a blocking function that it
	// should abandon its work after the timeout elapses.
	ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond)
	select {
	case <-time.After(200 * time.Millisecond):
		fmt.Println("overslept")
	case <-ctx.Done():
		fmt.Println(ctx.Err()) // prints "context deadline exceeded"
	}
}
Output:

context deadline exceeded

Types

type CancelFunc

type CancelFunc func()

A CancelFunc tells an operation to abandon its work. A CancelFunc does not wait for the work to stop. After the first, subsequent calls to a CancelFunc do nothing.

type Context

type Context interface {
	// Deadline returns the time when work done on behalf of this context
	// should be canceled.  Deadline returns ok==false when no deadline is
	// set.  Successive calls to Deadline return the same results.
	Deadline() (deadline time.Time, ok bool)

	// Done returns a channel that's closed when work done on behalf of this
	// context should be canceled.  Done may return nil if this context can
	// never become done.  Successive calls to Done return the same value.
	//
	// WithCancel arranges for Done to be closed when cancel is called;
	// WithDeadline arranges for Done to be closed when the deadline
	// expires; WithTimeout arranges for Done to be closed when the timeout
	// elapses.
	//
	// Done is provided for use in select statements:
	//
	//   // DoSomething calls DoSomethingSlow and returns as soon as
	//   // it returns or ctx.Done is closed.
	//   func DoSomething(ctx context.Context) (Result, error) {
	//     c := make(chan Result, 1)
	//     go func() { c <- DoSomethingSlow(ctx) }()
	//     select {
	//     case res := <-c:
	//       return res, nil
	//     case <-ctx.Done():
	//       return nil, ctx.Err()
	//     }
	//   }
	Done() <-chan struct{}

	// Err returns a non-nil error value after Done is closed.  Err returns
	// Canceled if the context was canceled; Err returns DeadlineExceeded if
	// the context's deadline passed.  No other values for Err are defined.
	Err() error

	// Value returns the value associated with this context for key, or nil
	// if no value is associated with key.  Successive calls to Value with
	// the same key returns the same result.
	Value(key Key) interface{}
}

A Context carries deadlines, and cancellation signals, and other values across API boundaries.

Context's methods may be called by multiple goroutines simultaneously.

func Background

func Background() Context

Background returns an ambient background context, which is never nil. This context represents the intrinsic state of the application at startup time, independent of any incoming request state.

The Background context is typically only used by the main function and tests.

func TODO

func TODO() Context

TODO returns an ambient background context, which is never nil. Code should use context.TODO when it's unclear which Context to use or it's is not yet available (because the surrounding function has not yet been extended to accept a Context parameter). TODO is recognized by static analysis tools that determine whether Contexts are propagated correctly in a program.

func WithValue

func WithValue(parent Context, k Key, v interface{}) Context

WithValue returns a copy of parent in which the value associated with k is v.

Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions.

type Key

type Key struct {
	// contains filtered or unexported fields
}

An Key identifies a specific Value in a Context. Functions that wish to store Values in Context typically allocate a Key in a global variable then use that Key as the argument to context.WithValue and Context.Value.

Packages that define a Context Key should provide type-safe accessors for the Values stores using that Key:

// package foo defines a value that's stored in Contexts.
package foo

import "code.google.com/p/go.net/context"

// Foo is the type of value stored in the Contexts.
type Foo struct {...}

// contextKey is the Key for foo.Foo values in Contexts.  It is
// unexported; foo clients use foo.NewContext and foo.FromContext
// instead of using this Key directly.
var contextKey = context.NewKey("import/path/of/foo.Foo")

// NewContext returns a new Context that carries value foo.
func NewContext(ctx context.Context, foo *Foo) context.Context {
  return context.WithValue(contextKey, foo)
}

// FromContext returns the Foo value stored in ctx, if any.
func FromContext(ctx context.Context) (*Foo, bool) {
  foo, ok := ctx.Value(contextKey).(*Foo)
  return foo, ok
}

func NewKey

func NewKey(name string) Key

NewKey allocates a new Key with the provided name. The name must be non-empty and globally unique: if NewKey is called multiple times with the same name it panics. NewKey should only be called during initalization.

func (Key) String

func (k Key) String() string

String returns the Key's name.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL