-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
83 lines (69 loc) · 2.09 KB
/
context.go
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
package core
import (
"context"
"fmt"
"time"
)
var (
_ fmt.Stringer = (*ContextKey[any])(nil)
_ fmt.GoStringer = (*ContextKey[any])(nil)
)
// ContextKey is a type-safe key for a context.Context value
type ContextKey[T any] struct {
name string
}
// WithValue safely attaches a value to a context.Context under this key.
func (ck *ContextKey[T]) WithValue(ctx context.Context, v T) context.Context {
switch ctx {
case nil, context.TODO():
ctx = context.Background()
}
return context.WithValue(ctx, ck, v)
}
// Get attempts to extract a value bound to this key in a [context.Context]
// For convenience this method will safely operate over a nil receiver.
func (ck *ContextKey[T]) Get(ctx context.Context) (T, bool) {
if ck == nil {
var zero T
return zero, false
}
v, ok := ctx.Value(ck).(T)
return v, ok
}
// String returns the name
func (ck *ContextKey[T]) String() string {
return ck.name
}
// GoString renders this key in Go syntax for %v
func (ck *ContextKey[T]) GoString() string {
var zero T
return fmt.Sprintf("core.NewContextKey[%T](%q)",
zero, ck.name)
}
// NewContextKey creates a new ContextKey bound to the
// specified type and friendly name
func NewContextKey[T any](name string) *ContextKey[T] {
return &ContextKey[T]{name: name}
}
// WithTimeout is equivalent to [context.WithDeadline] but taking a duration
// instead of an absolute time.
//
// If the duration is zero or negative the context won't expire.
func WithTimeout(parent context.Context, tio time.Duration) (context.Context, context.CancelFunc) {
if tio > 0 {
deadline := time.Now().Add(tio)
return context.WithDeadline(parent, deadline)
}
return parent, func() {}
}
// WithTimeoutCause is equivalent to [context.WithDeadlineCause] but taking a duration
// instead of an absolute time.
//
// If the duration is zero or negative the context won't expire.
func WithTimeoutCause(parent context.Context, tio time.Duration, cause error) (context.Context, context.CancelFunc) {
if tio > 0 {
deadline := time.Now().Add(tio)
return context.WithDeadlineCause(parent, deadline, cause)
}
return parent, func() {}
}