-
Notifications
You must be signed in to change notification settings - Fork 7
/
context.go
44 lines (36 loc) · 1.32 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
package progrock
import "context"
type recorderKey struct{}
// ToContext returns a new context with the given Recorder attached.
func ToContext(ctx context.Context, recorder *Recorder) context.Context {
return context.WithValue(ctx, recorderKey{}, recorder)
}
// FromContext returns the Recorder attached to the given context, or a no-op
// Recorder if none is attached.
func FromContext(ctx context.Context) *Recorder {
rec := ctx.Value(recorderKey{})
if rec == nil {
return NewRecorder(Discard{})
}
return rec.(*Recorder)
}
// WithGroup is shorthand for FromContext(ctx).WithGroup(name, opts...).
//
// It returns a new context with the resulting Recorder attached.
func WithGroup(ctx context.Context, name string, opts ...GroupOpt) (context.Context, *Recorder) {
rec := FromContext(ctx).WithGroup(name, opts...)
return ToContext(ctx, rec), rec
}
// RecorderToContext returns a new context with the given Recorder attached.
//
// Deprecated: use ToContext instead.
func RecorderToContext(ctx context.Context, recorder *Recorder) context.Context {
return ToContext(ctx, recorder)
}
// RecorderFromContext returns the Recorder attached to the given context, or a
// no-op Recorder if none is attached.
//
// Deprecated: use FromContext instead.
func RecorderFromContext(ctx context.Context) *Recorder {
return FromContext(ctx)
}