1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
|
<h1> Package context </h1> <ul id="short-nav">
<li><code>import "context"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
</ul> <h2 id="pkg-overview">Overview </h2> <p>Package context defines the Context type, which carries deadlines, cancellation signals, and other request-scoped values across API boundaries and between processes. </p>
<p>Incoming requests to a server should create a <a href="#Context">Context</a>, 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 <a href="#WithCancel">WithCancel</a>, <a href="#WithDeadline">WithDeadline</a>, <a href="#WithTimeout">WithTimeout</a>, or <a href="#WithValue">WithValue</a>. When a Context is canceled, all Contexts derived from it are also canceled. </p>
<p>The <a href="#WithCancel">WithCancel</a>, <a href="#WithDeadline">WithDeadline</a>, and <a href="#WithTimeout">WithTimeout</a> functions take a Context (the parent) and return a derived Context (the child) and a <a href="#CancelFunc">CancelFunc</a>. 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. </p>
<p>The <a href="#WithCancelCause">WithCancelCause</a> function returns a <a href="#CancelCauseFunc">CancelCauseFunc</a>, which takes an error and records it as the cancellation cause. Calling <a href="#Cause">Cause</a> on the canceled context or any of its children retrieves the cause. If no cause is specified, Cause(ctx) returns the same value as ctx.Err(). </p>
<p>Programs that use Contexts should follow these rules to keep interfaces consistent across packages and enable static analysis tools to check context propagation: </p>
<p>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: </p>
<pre data-language="go">func DoSomething(ctx context.Context, arg Arg) error {
// ... use ctx ...
}
</pre> <p>Do not pass a nil <a href="#Context">Context</a>, even if a function permits it. Pass <a href="#TODO">context.TODO</a> if you are unsure about which Context to use. </p>
<p>Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions. </p>
<p>The same Context may be passed to functions running in different goroutines; Contexts are safe for simultaneous use by multiple goroutines. </p>
<p>See <a href="https://blog.golang.org/context">https://blog.golang.org/context</a> for example code for a server that uses Contexts. </p> <h2 id="pkg-index">Index </h2> <ul id="manual-nav">
<li><a href="#pkg-variables">Variables</a></li>
<li><a href="#AfterFunc">func AfterFunc(ctx Context, f func()) (stop func() bool)</a></li>
<li><a href="#Cause">func Cause(c Context) error</a></li>
<li><a href="#WithCancel">func WithCancel(parent Context) (ctx Context, cancel CancelFunc)</a></li>
<li><a href="#WithCancelCause">func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)</a></li>
<li><a href="#WithDeadline">func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)</a></li>
<li><a href="#WithDeadlineCause">func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc)</a></li>
<li><a href="#WithTimeout">func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)</a></li>
<li><a href="#WithTimeoutCause">func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)</a></li>
<li><a href="#CancelCauseFunc">type CancelCauseFunc</a></li>
<li><a href="#CancelFunc">type CancelFunc</a></li>
<li><a href="#Context">type Context</a></li>
<li> <a href="#Background">func Background() Context</a>
</li>
<li> <a href="#TODO">func TODO() Context</a>
</li>
<li> <a href="#WithValue">func WithValue(parent Context, key, val any) Context</a>
</li>
<li> <a href="#WithoutCancel">func WithoutCancel(parent Context) Context</a>
</li>
</ul> <div id="pkg-examples"> <h3>Examples</h3> <dl> <dd><a class="exampleLink" href="#example_AfterFunc_cond">AfterFunc (Cond)</a></dd> <dd><a class="exampleLink" href="#example_AfterFunc_connection">AfterFunc (Connection)</a></dd> <dd><a class="exampleLink" href="#example_AfterFunc_merge">AfterFunc (Merge)</a></dd> <dd><a class="exampleLink" href="#example_WithCancel">WithCancel</a></dd> <dd><a class="exampleLink" href="#example_WithDeadline">WithDeadline</a></dd> <dd><a class="exampleLink" href="#example_WithTimeout">WithTimeout</a></dd> <dd><a class="exampleLink" href="#example_WithValue">WithValue</a></dd> </dl> </div> <h3>Package files</h3> <p> <span>context.go</span> </p> <h2 id="pkg-variables">Variables</h2> <p>Canceled is the error returned by [Context.Err] when the context is canceled. </p>
<pre data-language="go">var Canceled = errors.New("context canceled")</pre> <p>DeadlineExceeded is the error returned by [Context.Err] when the context's deadline passes. </p>
<pre data-language="go">var DeadlineExceeded error = deadlineExceededError{}</pre> <h2 id="AfterFunc">func <span>AfterFunc</span> <span title="Added in Go 1.21">1.21</span> </h2> <pre data-language="go">func AfterFunc(ctx Context, f func()) (stop func() bool)</pre> <p>AfterFunc arranges to call f in its own goroutine after ctx is done (cancelled or timed out). If ctx is already done, AfterFunc calls f immediately in its own goroutine. </p>
<p>Multiple calls to AfterFunc on a context operate independently; one does not replace another. </p>
<p>Calling the returned stop function stops the association of ctx with f. It returns true if the call stopped f from being run. If stop returns false, either the context is done and f has been started in its own goroutine; or f was already stopped. The stop function does not wait for f to complete before returning. If the caller needs to know whether f is completed, it must coordinate with f explicitly. </p>
<p>If ctx has a "AfterFunc(func()) func() bool" method, AfterFunc will use it to schedule the call. </p> <h4 id="example_AfterFunc_cond"> <span class="text">Example (Cond)</span>
</h4> <p>This example uses AfterFunc to define a function which waits on a sync.Cond, stopping the wait when a context is canceled. </p> <p>Code:</p> <pre class="code" data-language="go">waitOnCond := func(ctx context.Context, cond *sync.Cond, conditionMet func() bool) error {
stopf := context.AfterFunc(ctx, func() {
// We need to acquire cond.L here to be sure that the Broadcast
// below won't occur before the call to Wait, which would result
// in a missed signal (and deadlock).
cond.L.Lock()
defer cond.L.Unlock()
// If multiple goroutines are waiting on cond simultaneously,
// we need to make sure we wake up exactly this one.
// That means that we need to Broadcast to all of the goroutines,
// which will wake them all up.
//
// If there are N concurrent calls to waitOnCond, each of the goroutines
// will spuriously wake up O(N) other goroutines that aren't ready yet,
// so this will cause the overall CPU cost to be O(N²).
cond.Broadcast()
})
defer stopf()
// Since the wakeups are using Broadcast instead of Signal, this call to
// Wait may unblock due to some other goroutine's context becoming done,
// so to be sure that ctx is actually done we need to check it in a loop.
for !conditionMet() {
cond.Wait()
if ctx.Err() != nil {
return ctx.Err()
}
}
return nil
}
cond := sync.NewCond(new(sync.Mutex))
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
defer cancel()
cond.L.Lock()
defer cond.L.Unlock()
err := waitOnCond(ctx, cond, func() bool { return false })
fmt.Println(err)
}()
}
wg.Wait()
</pre> <p>Output:</p> <pre class="output" data-language="go">context deadline exceeded
context deadline exceeded
context deadline exceeded
context deadline exceeded
</pre> <h4 id="example_AfterFunc_connection"> <span class="text">Example (Connection)</span>
</h4> <p>This example uses AfterFunc to define a function which reads from a net.Conn, stopping the read when a context is canceled. </p> <p>Code:</p> <pre class="code" data-language="go">readFromConn := func(ctx context.Context, conn net.Conn, b []byte) (n int, err error) {
stopc := make(chan struct{})
stop := context.AfterFunc(ctx, func() {
conn.SetReadDeadline(time.Now())
close(stopc)
})
n, err = conn.Read(b)
if !stop() {
// The AfterFunc was started.
// Wait for it to complete, and reset the Conn's deadline.
<-stopc
conn.SetReadDeadline(time.Time{})
return n, ctx.Err()
}
return n, err
}
listener, err := net.Listen("tcp", ":0")
if err != nil {
fmt.Println(err)
return
}
defer listener.Close()
conn, err := net.Dial(listener.Addr().Network(), listener.Addr().String())
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Millisecond)
defer cancel()
b := make([]byte, 1024)
_, err = readFromConn(ctx, conn, b)
fmt.Println(err)
</pre> <p>Output:</p> <pre class="output" data-language="go">context deadline exceeded
</pre> <h4 id="example_AfterFunc_merge"> <span class="text">Example (Merge)</span>
</h4> <p>This example uses AfterFunc to define a function which combines the cancellation signals of two Contexts. </p> <p>Code:</p> <pre class="code" data-language="go">// mergeCancel returns a context that contains the values of ctx,
// and which is canceled when either ctx or cancelCtx is canceled.
mergeCancel := func(ctx, cancelCtx context.Context) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancelCause(ctx)
stop := context.AfterFunc(cancelCtx, func() {
cancel(context.Cause(cancelCtx))
})
return ctx, func() {
stop()
cancel(context.Canceled)
}
}
ctx1, cancel1 := context.WithCancelCause(context.Background())
defer cancel1(errors.New("ctx1 canceled"))
ctx2, cancel2 := context.WithCancelCause(context.Background())
mergedCtx, mergedCancel := mergeCancel(ctx1, ctx2)
defer mergedCancel()
cancel2(errors.New("ctx2 canceled"))
<-mergedCtx.Done()
fmt.Println(context.Cause(mergedCtx))
</pre> <p>Output:</p> <pre class="output" data-language="go">ctx2 canceled
</pre> <h2 id="Cause">func <span>Cause</span> <span title="Added in Go 1.20">1.20</span> </h2> <pre data-language="go">func Cause(c Context) error</pre> <p>Cause returns a non-nil error explaining why c was canceled. The first cancellation of c or one of its parents sets the cause. If that cancellation happened via a call to CancelCauseFunc(err), then <a href="#Cause">Cause</a> returns err. Otherwise Cause(c) returns the same value as c.Err(). Cause returns nil if c has not been canceled yet. </p>
<h2 id="WithCancel">func <span>WithCancel</span> <span title="Added in Go 1.7">1.7</span> </h2> <pre data-language="go">func WithCancel(parent Context) (ctx Context, cancel CancelFunc)</pre> <p>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. </p>
<p>Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this Context complete. </p> <h4 id="example_WithCancel"> <span class="text">Example</span>
</h4> <p>This example demonstrates the use of a cancelable context to prevent a goroutine leak. By the end of the example function, the goroutine started by gen will return without leaking. </p> <p>Code:</p> <pre class="code" data-language="go">// gen generates integers in a separate goroutine and
// sends them to the returned channel.
// The callers of gen need to cancel the context once
// they are done consuming generated integers not to leak
// the internal goroutine started by gen.
gen := func(ctx context.Context) <-chan int {
dst := make(chan int)
n := 1
go func() {
for {
select {
case <-ctx.Done():
return // returning not to leak the goroutine
case dst <- n:
n++
}
}
}()
return dst
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel() // cancel when we are finished consuming integers
for n := range gen(ctx) {
fmt.Println(n)
if n == 5 {
break
}
}
</pre> <p>Output:</p> <pre class="output" data-language="go">1
2
3
4
5
</pre> <h2 id="WithCancelCause">func <span>WithCancelCause</span> <span title="Added in Go 1.20">1.20</span> </h2> <pre data-language="go">func WithCancelCause(parent Context) (ctx Context, cancel CancelCauseFunc)</pre> <p>WithCancelCause behaves like <a href="#WithCancel">WithCancel</a> but returns a <a href="#CancelCauseFunc">CancelCauseFunc</a> instead of a <a href="#CancelFunc">CancelFunc</a>. Calling cancel with a non-nil error (the "cause") records that error in ctx; it can then be retrieved using Cause(ctx). Calling cancel with nil sets the cause to Canceled. </p>
<p>Example use: </p>
<pre data-language="go">ctx, cancel := context.WithCancelCause(parent)
cancel(myError)
ctx.Err() // returns context.Canceled
context.Cause(ctx) // returns myError
</pre> <h2 id="WithDeadline">func <span>WithDeadline</span> <span title="Added in Go 1.7">1.7</span> </h2> <pre data-language="go">func WithDeadline(parent Context, d time.Time) (Context, CancelFunc)</pre> <p>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.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. </p>
<p>Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this <a href="#Context">Context</a> complete. </p> <h4 id="example_WithDeadline"> <span class="text">Example</span>
</h4> <p>This example passes a context with an arbitrary deadline to tell a blocking function that it should abandon its work as soon as it gets to it. </p> <p>Code:</p> <pre class="code" data-language="go">d := time.Now().Add(shortDuration)
ctx, cancel := context.WithDeadline(context.Background(), d)
// Even though ctx will be expired, it is good practice to call its
// cancellation function in any case. Failure to do so may keep the
// context and its parent alive longer than necessary.
defer cancel()
select {
case <-neverReady:
fmt.Println("ready")
case <-ctx.Done():
fmt.Println(ctx.Err())
}
</pre> <p>Output:</p> <pre class="output" data-language="go">context deadline exceeded
</pre> <h2 id="WithDeadlineCause">func <span>WithDeadlineCause</span> <span title="Added in Go 1.21">1.21</span> </h2> <pre data-language="go">func WithDeadlineCause(parent Context, d time.Time, cause error) (Context, CancelFunc)</pre> <p>WithDeadlineCause behaves like <a href="#WithDeadline">WithDeadline</a> but also sets the cause of the returned Context when the deadline is exceeded. The returned <a href="#CancelFunc">CancelFunc</a> does not set the cause. </p>
<h2 id="WithTimeout">func <span>WithTimeout</span> <span title="Added in Go 1.7">1.7</span> </h2> <pre data-language="go">func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)</pre> <p>WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). </p>
<p>Canceling this context releases resources associated with it, so code should call cancel as soon as the operations running in this <a href="#Context">Context</a> complete: </p>
<pre data-language="go">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)
}
</pre> <h4 id="example_WithTimeout"> <span class="text">Example</span>
</h4> <p>This example passes a context with a timeout to tell a blocking function that it should abandon its work after the timeout elapses. </p> <p>Code:</p> <pre class="code" data-language="go">// Pass a context with a timeout to tell a blocking function that it
// should abandon its work after the timeout elapses.
ctx, cancel := context.WithTimeout(context.Background(), shortDuration)
defer cancel()
select {
case <-neverReady:
fmt.Println("ready")
case <-ctx.Done():
fmt.Println(ctx.Err()) // prints "context deadline exceeded"
}
</pre> <p>Output:</p> <pre class="output" data-language="go">context deadline exceeded
</pre> <h2 id="WithTimeoutCause">func <span>WithTimeoutCause</span> <span title="Added in Go 1.21">1.21</span> </h2> <pre data-language="go">func WithTimeoutCause(parent Context, timeout time.Duration, cause error) (Context, CancelFunc)</pre> <p>WithTimeoutCause behaves like <a href="#WithTimeout">WithTimeout</a> but also sets the cause of the returned Context when the timeout expires. The returned <a href="#CancelFunc">CancelFunc</a> does not set the cause. </p>
<h2 id="CancelCauseFunc">type <span>CancelCauseFunc</span> <span title="Added in Go 1.20">1.20</span> </h2> <p>A CancelCauseFunc behaves like a <a href="#CancelFunc">CancelFunc</a> but additionally sets the cancellation cause. This cause can be retrieved by calling <a href="#Cause">Cause</a> on the canceled Context or on any of its derived Contexts. </p>
<p>If the context has already been canceled, CancelCauseFunc does not set the cause. For example, if childContext is derived from parentContext: </p>
<ul> <li>if parentContext is canceled with cause1 before childContext is canceled with cause2, then Cause(parentContext) == Cause(childContext) == cause1 </li>
<li>if childContext is canceled with cause2 before parentContext is canceled with cause1, then Cause(parentContext) == cause1 and Cause(childContext) == cause2 </li>
</ul> <pre data-language="go">type CancelCauseFunc func(cause error)</pre> <h2 id="CancelFunc">type <span>CancelFunc</span> <span title="Added in Go 1.7">1.7</span> </h2> <p>A CancelFunc tells an operation to abandon its work. A CancelFunc does not wait for the work to stop. A CancelFunc may be called by multiple goroutines simultaneously. After the first call, subsequent calls to a CancelFunc do nothing. </p>
<pre data-language="go">type CancelFunc func()</pre> <h2 id="Context">type <span>Context</span> <span title="Added in Go 1.7">1.7</span> </h2> <p>A Context carries a deadline, a cancellation signal, and other values across API boundaries. </p>
<p>Context's methods may be called by multiple goroutines simultaneously. </p>
<pre data-language="go">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 be canceled. Successive calls to Done return the same value.
// The close of the Done channel may happen asynchronously,
// after the cancel function returns.
//
// 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:
//
// // Stream generates values with DoSomething and sends them to out
// // until DoSomething returns an error or ctx.Done is closed.
// func Stream(ctx context.Context, out chan<- Value) error {
// for {
// v, err := DoSomething(ctx)
// if err != nil {
// return err
// }
// select {
// case <-ctx.Done():
// return ctx.Err()
// case out <- v:
// }
// }
// }
//
// See https://blog.golang.org/pipelines for more examples of how to use
// a Done channel for cancellation.
Done() <-chan struct{}
// If Done is not yet closed, Err returns nil.
// If Done is closed, Err returns a non-nil error explaining why:
// Canceled if the context was canceled
// or DeadlineExceeded if the context's deadline passed.
// After Err returns a non-nil error, successive calls to Err return the same error.
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.
//
// Use context values only for request-scoped data that transits
// processes and API boundaries, not for passing optional parameters to
// functions.
//
// A 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. A key can be any type that supports equality;
// packages should define keys as an unexported type to avoid
// collisions.
//
// Packages that define a Context key should provide type-safe accessors
// for the values stored using that key:
//
// // Package user defines a User type that's stored in Contexts.
// package user
//
// import "context"
//
// // User is the type of value stored in the Contexts.
// type User struct {...}
//
// // key is an unexported type for keys defined in this package.
// // This prevents collisions with keys defined in other packages.
// type key int
//
// // userKey is the key for user.User values in Contexts. It is
// // unexported; clients use user.NewContext and user.FromContext
// // instead of using this key directly.
// var userKey key
//
// // NewContext returns a new Context that carries value u.
// func NewContext(ctx context.Context, u *User) context.Context {
// return context.WithValue(ctx, userKey, u)
// }
//
// // FromContext returns the User value stored in ctx, if any.
// func FromContext(ctx context.Context) (*User, bool) {
// u, ok := ctx.Value(userKey).(*User)
// return u, ok
// }
Value(key any) any
}</pre> <h3 id="Background">func <span>Background</span> <span title="Added in Go 1.7">1.7</span> </h3> <pre data-language="go">func Background() Context</pre> <p>Background returns a non-nil, empty <a href="#Context">Context</a>. 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. </p>
<h3 id="TODO">func <span>TODO</span> <span title="Added in Go 1.7">1.7</span> </h3> <pre data-language="go">func TODO() Context</pre> <p>TODO returns a non-nil, empty <a href="#Context">Context</a>. 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). </p>
<h3 id="WithValue">func <span>WithValue</span> <span title="Added in Go 1.7">1.7</span> </h3> <pre data-language="go">func WithValue(parent Context, key, val any) Context</pre> <p>WithValue returns a copy of parent in which the value associated with key is val. </p>
<p>Use context Values only for request-scoped data that transits processes and APIs, not for passing optional parameters to functions. </p>
<p>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. </p> <h4 id="example_WithValue"> <span class="text">Example</span>
</h4> <p>This example demonstrates how a value can be passed to the context and also how to retrieve it if it exists. </p> <p>Code:</p> <pre class="code" data-language="go">type favContextKey string
f := func(ctx context.Context, k favContextKey) {
if v := ctx.Value(k); v != nil {
fmt.Println("found value:", v)
return
}
fmt.Println("key not found:", k)
}
k := favContextKey("language")
ctx := context.WithValue(context.Background(), k, "Go")
f(ctx, k)
f(ctx, favContextKey("color"))
</pre> <p>Output:</p> <pre class="output" data-language="go">found value: Go
key not found: color
</pre> <h3 id="WithoutCancel">func <span>WithoutCancel</span> <span title="Added in Go 1.21">1.21</span> </h3> <pre data-language="go">func WithoutCancel(parent Context) Context</pre> <p>WithoutCancel returns a copy of parent that is not canceled when parent is canceled. The returned context returns no Deadline or Err, and its Done channel is nil. Calling <a href="#Cause">Cause</a> on the returned context returns nil. </p><div class="_attribution">
<p class="_attribution-p">
© Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
<a href="http://golang.org/pkg/context/" class="_attribution-link">http://golang.org/pkg/context/</a>
</p>
</div>
|