version: 1.10

package context

import "context"

Overview

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

Incoming requests to a server should create a Context, and outgoing calls to servers should accept a Context. The chain of function calls between them must propagate the Context, optionally replacing it with a derived Context created using WithCancel, WithDeadline, WithTimeout, or WithValue. When a Context is canceled, all Contexts derived from it are also canceled.

The WithCancel, WithDeadline, and WithTimeout functions take a Context (the parent) and return a derived Context (the child) and a CancelFunc. Calling the CancelFunc cancels the child and its children, removes the parent’s reference to the child, and stops any associated timers. Failing to call the CancelFunc leaks the child and its children until the parent is canceled or the timer fires. The go vet tool checks that CancelFuncs are used on all control-flow paths.

Programs that use Contexts should follow these rules to keep interfaces consistent across packages and enable static analysis tools to check context propagation:

Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx:

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

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

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

The same Context may be passed to functions running in different goroutines; Contexts are safe for simultaneous use by multiple goroutines.

See https://blog.golang.org/context for example code for a server that uses Contexts.

Index

Examples

Package files

context.go

Variables

  1. var Canceled = errors.New("context canceled")

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

  1. var DeadlineExceeded error = deadlineExceededError{}

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

type CancelFunc

  1. 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 call, subsequent calls to a CancelFunc do nothing.

type Context

  1. type Context interface {
  2. // Deadline returns the time when work done on behalf of this context
  3. // should be canceled. Deadline returns ok==false when no deadline is
  4. // set. Successive calls to Deadline return the same results.
  5. Deadline() (deadline time.Time, ok bool)
  6.  
  7. // Done returns a channel that's closed when work done on behalf of this
  8. // context should be canceled. Done may return nil if this context can
  9. // never be canceled. Successive calls to Done return the same value.
  10. //
  11. // WithCancel arranges for Done to be closed when cancel is called;
  12. // WithDeadline arranges for Done to be closed when the deadline
  13. // expires; WithTimeout arranges for Done to be closed when the timeout
  14. // elapses.
  15. //
  16. // Done is provided for use in select statements:
  17. //
  18. // // Stream generates values with DoSomething and sends them to out
  19. // // until DoSomething returns an error or ctx.Done is closed.
  20. // func Stream(ctx context.Context, out chan<- Value) error {
  21. // for {
  22. // v, err := DoSomething(ctx)
  23. // if err != nil {
  24. // return err
  25. // }
  26. // select {
  27. // case <-ctx.Done():
  28. // return ctx.Err()
  29. // case out <- v:
  30. // }
  31. // }
  32. // }
  33. //
  34. // See https://blog.golang.org/pipelines for more examples of how to use
  35. // a Done channel for cancelation.
  36. Done() <-chan struct{}
  37.  
  38. // If Done is not yet closed, Err returns nil.
  39. // If Done is closed, Err returns a non-nil error explaining why:
  40. // Canceled if the context was canceled
  41. // or DeadlineExceeded if the context's deadline passed.
  42. // After Err returns a non-nil error, successive calls to Err return the same error.
  43. Err() error
  44.  
  45. // Value returns the value associated with this context for key, or nil
  46. // if no value is associated with key. Successive calls to Value with
  47. // the same key returns the same result.
  48. //
  49. // Use context values only for request-scoped data that transits
  50. // processes and API boundaries, not for passing optional parameters to
  51. // functions.
  52. //
  53. // A key identifies a specific value in a Context. Functions that wish
  54. // to store values in Context typically allocate a key in a global
  55. // variable then use that key as the argument to context.WithValue and
  56. // Context.Value. A key can be any type that supports equality;
  57. // packages should define keys as an unexported type to avoid
  58. // collisions.
  59. //
  60. // Packages that define a Context key should provide type-safe accessors
  61. // for the values stored using that key:
  62. //
  63. // // Package user defines a User type that's stored in Contexts.
  64. // package user
  65. //
  66. // import "context"
  67. //
  68. // // User is the type of value stored in the Contexts.
  69. // type User struct {...}
  70. //
  71. // // key is an unexported type for keys defined in this package.
  72. // // This prevents collisions with keys defined in other packages.
  73. // type key int
  74. //
  75. // // userKey is the key for user.User values in Contexts. It is
  76. // // unexported; clients use user.NewContext and user.FromContext
  77. // // instead of using this key directly.
  78. // var userKey key
  79. //
  80. // // NewContext returns a new Context that carries value u.
  81. // func NewContext(ctx context.Context, u *User) context.Context {
  82. // return context.WithValue(ctx, userKey, u)
  83. // }
  84. //
  85. // // FromContext returns the User value stored in ctx, if any.
  86. // func FromContext(ctx context.Context) (*User, bool) {
  87. // u, ok := ctx.Value(userKey).(*User)
  88. // return u, ok
  89. // }
  90. Value(key interface{}) interface{}
  91. }

A Context carries a deadline, a cancelation signal, and other values across API boundaries.

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

func Background

  1. func Background() Context

Background returns a non-nil, empty Context. It is never canceled, has no values, and has no deadline. It is typically used by the main function, initialization, and tests, and as the top-level Context for incoming requests.

func TODO

  1. func TODO() Context

TODO returns a non-nil, empty Context. Code should use context.TODO when it’s unclear which Context to use or it 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 WithCancel

  1. 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.

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

Example:

  1. // gen generates integers in a separate goroutine and
  2. // sends them to the returned channel.
  3. // The callers of gen need to cancel the context once
  4. // they are done consuming generated integers not to leak
  5. // the internal goroutine started by gen.
  6. gen := func(ctx context.Context) <-chan int {
  7. dst := make(chan int)
  8. n := 1
  9. go func() {
  10. for {
  11. select {
  12. case <-ctx.Done():
  13. return // returning not to leak the goroutine
  14. case dst <- n:
  15. n++
  16. }
  17. }
  18. }()
  19. return dst
  20. }
  21. ctx, cancel := context.WithCancel(context.Background())
  22. defer cancel() // cancel when we are finished consuming integers
  23. for n := range gen(ctx) {
  24. fmt.Println(n)
  25. if n == 5 {
  26. break
  27. }
  28. }
  29. // Output:
  30. // 1
  31. // 2
  32. // 3
  33. // 4
  34. // 5

func WithDeadline

  1. func WithDeadline(parent Context, d 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.

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

Example:

  1. d := time.Now().Add(50 * time.Millisecond)
  2. ctx, cancel := context.WithDeadline(context.Background(), d)
  3. // Even though ctx will be expired, it is good practice to call its
  4. // cancelation function in any case. Failure to do so may keep the
  5. // context and its parent alive longer than necessary.
  6. defer cancel()
  7. select {
  8. case <-time.After(1 * time.Second):
  9. fmt.Println("overslept")
  10. case <-ctx.Done():
  11. fmt.Println(ctx.Err())
  12. }
  13. // Output:
  14. // context deadline exceeded

func WithTimeout

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

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

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

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

Example:

  1. // Pass a context with a timeout to tell a blocking function that it
  2. // should abandon its work after the timeout elapses.
  3. ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
  4. defer cancel()
  5. select {
  6. case <-time.After(1 * time.Second):
  7. fmt.Println("overslept")
  8. case <-ctx.Done():
  9. fmt.Println(ctx.Err()) // prints "context deadline exceeded"
  10. }
  11. // Output:
  12. // context deadline exceeded

func WithValue

  1. func WithValue(parent Context, key, val interface{}) Context

WithValue returns a copy of parent in which the value associated with key is val.

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

The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys. To avoid allocating when assigning to an interface{}, context keys often have concrete type struct{}. Alternatively, exported context key variables’ static type should be a pointer or interface.

Example:

  1. type favContextKey string
  2. f := func(ctx context.Context, k favContextKey) {
  3. if v := ctx.Value(k); v != nil {
  4. fmt.Println("found value:", v)
  5. return
  6. }
  7. fmt.Println("key not found:", k)
  8. }
  9. k := favContextKey("language")
  10. ctx := context.WithValue(context.Background(), k, "Go")
  11. f(ctx, k)
  12. f(ctx, favContextKey("color"))
  13. // Output:
  14. // found value: Go
  15. // key not found: color