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