File: context.go

package info (click to toggle)
dnss 0.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 368 kB
  • sloc: sh: 237; makefile: 6
file content (40 lines) | stat: -rw-r--r-- 1,075 bytes parent folder | download
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
package nettrace

import "context"

type ctxKeyT string

const ctxKey ctxKeyT = "blitiri.com.ar/go/nettrace"

// NewContext returns a new context with the given trace attached.
func NewContext(ctx context.Context, tr Trace) context.Context {
	return context.WithValue(ctx, ctxKey, tr)
}

// FromContext returns the trace attached to the given context (if any).
func FromContext(ctx context.Context) (Trace, bool) {
	tr, ok := ctx.Value(ctxKey).(Trace)
	return tr, ok
}

// FromContextOrNew returns the trace attached to the given context, or a new
// trace if there is none.
func FromContextOrNew(ctx context.Context, family, title string) (Trace, context.Context) {
	tr, ok := FromContext(ctx)
	if ok {
		return tr, ctx
	}

	tr = New(family, title)
	return tr, NewContext(ctx, tr)
}

// ChildFromContext returns a new trace that is a child of the one attached to
// the context (if any).
func ChildFromContext(ctx context.Context, family, title string) Trace {
	parent, ok := FromContext(ctx)
	if ok {
		return parent.NewChild(family, title)
	}
	return New(family, title)
}