1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3 4 package trace // import "go.opentelemetry.io/otel/trace"
5 6 import "context"
7 8 type traceContextKeyType int
9 10 const currentSpanKey traceContextKeyType = iota
11 12 // ContextWithSpan returns a copy of parent with span set as the current Span.
13 func ContextWithSpan(parent context.Context, span Span) context.Context {
14 return context.WithValue(parent, currentSpanKey, span)
15 }
16 17 // ContextWithSpanContext returns a copy of parent with sc as the current
18 // Span. The Span implementation that wraps sc is non-recording and performs
19 // no operations other than to return sc as the SpanContext from the
20 // SpanContext method.
21 func ContextWithSpanContext(parent context.Context, sc SpanContext) context.Context {
22 return ContextWithSpan(parent, nonRecordingSpan{sc: sc})
23 }
24 25 // ContextWithRemoteSpanContext returns a copy of parent with rsc set explicitly
26 // as a remote SpanContext and as the current Span. The Span implementation
27 // that wraps rsc is non-recording and performs no operations other than to
28 // return rsc as the SpanContext from the SpanContext method.
29 func ContextWithRemoteSpanContext(parent context.Context, rsc SpanContext) context.Context {
30 return ContextWithSpanContext(parent, rsc.WithRemote(true))
31 }
32 33 // SpanFromContext returns the current Span from ctx.
34 //
35 // If no Span is currently set in ctx an implementation of a Span that
36 // performs no operations is returned.
37 func SpanFromContext(ctx context.Context) Span {
38 if ctx == nil {
39 return noopSpanInstance
40 }
41 if span, ok := ctx.Value(currentSpanKey).(Span); ok {
42 return span
43 }
44 return noopSpanInstance
45 }
46 47 // SpanContextFromContext returns the current Span's SpanContext.
48 func SpanContextFromContext(ctx context.Context) SpanContext {
49 return SpanFromContext(ctx).SpanContext()
50 }
51