File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ package context
2
+
3
+ import (
4
+ "context"
5
+ "time"
6
+ )
7
+
8
+ type detached struct {
9
+ ctx context.Context
10
+ }
11
+
12
+ func (detached ) Deadline () (time.Time , bool ) {
13
+ return time.Time {}, false
14
+ }
15
+
16
+ func (detached ) Done () <- chan struct {} {
17
+ return nil
18
+ }
19
+
20
+ func (detached ) Err () error {
21
+ return nil
22
+ }
23
+
24
+ func (d detached ) Value (key interface {}) interface {} {
25
+ return d .ctx .Value (key )
26
+ }
27
+
28
+ // Detach creates a detached context (without cancel and deadline) from a parent ctx.
29
+ // Example:
30
+ // import myapp/context
31
+ // func home(w http.ResponseWriter, r *http.Request) {
32
+ // log.Println("home")
33
+ // // Create a Detached context
34
+ // detachedCtx := context.Detach(r.Context())
35
+ // detachedDeadline, ok := detachedCtx.Deadline()
36
+ // fmt.Println("DETACHED ---")
37
+ // fmt.Println("Deadline():", detachedDeadline, ok) // 0001-01-01 00:00:00 +0000 UTC false
38
+ // fmt.Println("Err():", r.Context().Err()) // <empty>
39
+ // backgroundTask.Run(detachedCtx) // prevents task stop when r.Context has cancelled
40
+ // }
41
+ func Detach (ctx context.Context ) context.Context {
42
+ return detached {ctx : ctx }
43
+ }
You can’t perform that action at this time.
0 commit comments