context.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package context defines the Context type, which carries deadlines,
  5. // cancellation signals, and other request-scoped values across API boundaries
  6. // and between processes.
  7. // As of Go 1.7 this package is available in the standard library under the
  8. // name [context], and migrating to it can be done automatically with [go fix].
  9. //
  10. // Incoming requests to a server should create a [Context], and outgoing
  11. // calls to servers should accept a Context. The chain of function
  12. // calls between them must propagate the Context, optionally replacing
  13. // it with a derived Context created using [WithCancel], [WithDeadline],
  14. // [WithTimeout], or [WithValue].
  15. //
  16. // Programs that use Contexts should follow these rules to keep interfaces
  17. // consistent across packages and enable static analysis tools to check context
  18. // propagation:
  19. //
  20. // Do not store Contexts inside a struct type; instead, pass a Context
  21. // explicitly to each function that needs it. This is discussed further in
  22. // https://go.dev/blog/context-and-structs. The Context should be the first
  23. // parameter, typically named ctx:
  24. //
  25. // func DoSomething(ctx context.Context, arg Arg) error {
  26. // // ... use ctx ...
  27. // }
  28. //
  29. // Do not pass a nil [Context], even if a function permits it. Pass [context.TODO]
  30. // if you are unsure about which Context to use.
  31. //
  32. // Use context Values only for request-scoped data that transits processes and
  33. // APIs, not for passing optional parameters to functions.
  34. //
  35. // The same Context may be passed to functions running in different goroutines;
  36. // Contexts are safe for simultaneous use by multiple goroutines.
  37. //
  38. // See https://go.dev/blog/context for example code for a server that uses
  39. // Contexts.
  40. //
  41. // [go fix]: https://go.dev/cmd/go#hdr-Update_packages_to_use_new_APIs
  42. package context
  43. import (
  44. "context" // standard library's context, as of Go 1.7
  45. "time"
  46. )
  47. // A Context carries a deadline, a cancellation signal, and other values across
  48. // API boundaries.
  49. //
  50. // Context's methods may be called by multiple goroutines simultaneously.
  51. type Context = context.Context
  52. // Canceled is the error returned by [Context.Err] when the context is canceled
  53. // for some reason other than its deadline passing.
  54. var Canceled = context.Canceled
  55. // DeadlineExceeded is the error returned by [Context.Err] when the context is canceled
  56. // due to its deadline passing.
  57. var DeadlineExceeded = context.DeadlineExceeded
  58. // Background returns a non-nil, empty Context. It is never canceled, has no
  59. // values, and has no deadline. It is typically used by the main function,
  60. // initialization, and tests, and as the top-level Context for incoming
  61. // requests.
  62. func Background() Context {
  63. return background
  64. }
  65. // TODO returns a non-nil, empty Context. Code should use context.TODO when
  66. // it's unclear which Context to use or it is not yet available (because the
  67. // surrounding function has not yet been extended to accept a Context
  68. // parameter).
  69. func TODO() Context {
  70. return todo
  71. }
  72. var (
  73. background = context.Background()
  74. todo = context.TODO()
  75. )
  76. // A CancelFunc tells an operation to abandon its work.
  77. // A CancelFunc does not wait for the work to stop.
  78. // A CancelFunc may be called by multiple goroutines simultaneously.
  79. // After the first call, subsequent calls to a CancelFunc do nothing.
  80. type CancelFunc = context.CancelFunc
  81. // WithCancel returns a derived context that points to the parent context
  82. // but has a new Done channel. The returned context's Done channel is closed
  83. // when the returned cancel function is called or when the parent context's
  84. // Done channel is closed, whichever happens first.
  85. //
  86. // Canceling this context releases resources associated with it, so code should
  87. // call cancel as soon as the operations running in this [Context] complete.
  88. func WithCancel(parent Context) (ctx Context, cancel CancelFunc) {
  89. return context.WithCancel(parent)
  90. }
  91. // WithDeadline returns a derived context that points to the parent context
  92. // but has the deadline adjusted to be no later than d. If the parent's
  93. // deadline is already earlier than d, WithDeadline(parent, d) is semantically
  94. // equivalent to parent. The returned [Context.Done] channel is closed when
  95. // the deadline expires, when the returned cancel function is called,
  96. // or when the parent context's Done channel is closed, whichever happens first.
  97. //
  98. // Canceling this context releases resources associated with it, so code should
  99. // call cancel as soon as the operations running in this [Context] complete.
  100. func WithDeadline(parent Context, d time.Time) (Context, CancelFunc) {
  101. return context.WithDeadline(parent, d)
  102. }
  103. // WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
  104. //
  105. // Canceling this context releases resources associated with it, so code should
  106. // call cancel as soon as the operations running in this [Context] complete:
  107. //
  108. // func slowOperationWithTimeout(ctx context.Context) (Result, error) {
  109. // ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
  110. // defer cancel() // releases resources if slowOperation completes before timeout elapses
  111. // return slowOperation(ctx)
  112. // }
  113. func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) {
  114. return context.WithTimeout(parent, timeout)
  115. }
  116. // WithValue returns a derived context that points to the parent Context.
  117. // In the derived context, the value associated with key is val.
  118. //
  119. // Use context Values only for request-scoped data that transits processes and
  120. // APIs, not for passing optional parameters to functions.
  121. //
  122. // The provided key must be comparable and should not be of type
  123. // string or any other built-in type to avoid collisions between
  124. // packages using context. Users of WithValue should define their own
  125. // types for keys. To avoid allocating when assigning to an
  126. // interface{}, context keys often have concrete type
  127. // struct{}. Alternatively, exported context key variables' static
  128. // type should be a pointer or interface.
  129. func WithValue(parent Context, key, val interface{}) Context {
  130. return context.WithValue(parent, key, val)
  131. }