context.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. // cancelation 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. https://golang.org/pkg/context.
  9. //
  10. // Incoming requests to a server should create a Context, and outgoing calls to
  11. // servers should accept a Context. The chain of function calls between must
  12. // propagate the Context, optionally replacing it with a modified copy created
  13. // using WithDeadline, WithTimeout, WithCancel, or WithValue.
  14. //
  15. // Programs that use Contexts should follow these rules to keep interfaces
  16. // consistent across packages and enable static analysis tools to check context
  17. // propagation:
  18. //
  19. // Do not store Contexts inside a struct type; instead, pass a Context
  20. // explicitly to each function that needs it. The Context should be the first
  21. // parameter, typically named ctx:
  22. //
  23. // func DoSomething(ctx context.Context, arg Arg) error {
  24. // // ... use ctx ...
  25. // }
  26. //
  27. // Do not pass a nil Context, even if a function permits it. Pass context.TODO
  28. // if you are unsure about which Context to use.
  29. //
  30. // Use context Values only for request-scoped data that transits processes and
  31. // APIs, not for passing optional parameters to functions.
  32. //
  33. // The same Context may be passed to functions running in different goroutines;
  34. // Contexts are safe for simultaneous use by multiple goroutines.
  35. //
  36. // See http://blog.golang.org/context for example code for a server that uses
  37. // Contexts.
  38. package context // import "golang.org/x/net/context"
  39. // Background returns a non-nil, empty Context. It is never canceled, has no
  40. // values, and has no deadline. It is typically used by the main function,
  41. // initialization, and tests, and as the top-level Context for incoming
  42. // requests.
  43. func Background() Context {
  44. return background
  45. }
  46. // TODO returns a non-nil, empty Context. Code should use context.TODO when
  47. // it's unclear which Context to use or it is not yet available (because the
  48. // surrounding function has not yet been extended to accept a Context
  49. // parameter). TODO is recognized by static analysis tools that determine
  50. // whether Contexts are propagated correctly in a program.
  51. func TODO() Context {
  52. return todo
  53. }