Skip to content

Commit 6cf0dfa

Browse files
author
Dmitry Sinyavskiy
committed
Added detached context example
1 parent 8b50359 commit 6cf0dfa

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

context/detached.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

0 commit comments

Comments
 (0)