1package opentracing
2
3import "context"
4
5type contextKey struct{}
6
7var activeSpanKey = contextKey{}
8
9// ContextWithSpan returns a new `context.Context` that holds a reference to
10// the span. If span is nil, a new context without an active span is returned.
11func ContextWithSpan(ctx context.Context, span Span) context.Context {
12	if span != nil {
13		if tracerWithHook, ok := span.Tracer().(TracerContextWithSpanExtension); ok {
14			ctx = tracerWithHook.ContextWithSpanHook(ctx, span)
15		}
16	}
17	return context.WithValue(ctx, activeSpanKey, span)
18}
19
20// SpanFromContext returns the `Span` previously associated with `ctx`, or
21// `nil` if no such `Span` could be found.
22//
23// NOTE: context.Context != SpanContext: the former is Go's intra-process
24// context propagation mechanism, and the latter houses OpenTracing's per-Span
25// identity and baggage information.
26func SpanFromContext(ctx context.Context) Span {
27	val := ctx.Value(activeSpanKey)
28	if sp, ok := val.(Span); ok {
29		return sp
30	}
31	return nil
32}
33
34// StartSpanFromContext starts and returns a Span with `operationName`, using
35// any Span found within `ctx` as a ChildOfRef. If no such parent could be
36// found, StartSpanFromContext creates a root (parentless) Span.
37//
38// The second return value is a context.Context object built around the
39// returned Span.
40//
41// Example usage:
42//
43//    SomeFunction(ctx context.Context, ...) {
44//        sp, ctx := opentracing.StartSpanFromContext(ctx, "SomeFunction")
45//        defer sp.Finish()
46//        ...
47//    }
48func StartSpanFromContext(ctx context.Context, operationName string, opts ...StartSpanOption) (Span, context.Context) {
49	return StartSpanFromContextWithTracer(ctx, GlobalTracer(), operationName, opts...)
50}
51
52// StartSpanFromContextWithTracer starts and returns a span with `operationName`
53// using  a span found within the context as a ChildOfRef. If that doesn't exist
54// it creates a root span. It also returns a context.Context object built
55// around the returned span.
56//
57// It's behavior is identical to StartSpanFromContext except that it takes an explicit
58// tracer as opposed to using the global tracer.
59func StartSpanFromContextWithTracer(ctx context.Context, tracer Tracer, operationName string, opts ...StartSpanOption) (Span, context.Context) {
60	if parentSpan := SpanFromContext(ctx); parentSpan != nil {
61		opts = append(opts, ChildOf(parentSpan.Context()))
62	}
63	span := tracer.StartSpan(operationName, opts...)
64	return span, ContextWithSpan(ctx, span)
65}
66