1// Copyright 2019 The OpenZipkin Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package zipkin
16
17import (
18	"context"
19)
20
21var defaultNoopSpan = &noopSpan{}
22
23// SpanFromContext retrieves a Zipkin Span from Go's context propagation
24// mechanism if found. If not found, returns nil.
25func SpanFromContext(ctx context.Context) Span {
26	if s, ok := ctx.Value(spanKey).(Span); ok {
27		return s
28	}
29	return nil
30}
31
32// SpanOrNoopFromContext retrieves a Zipkin Span from Go's context propagation
33// mechanism if found. If not found, returns a noopSpan.
34// This function typically is used for modules that want to provide existing
35// Zipkin spans with additional data, but can't guarantee that spans are
36// properly propagated. It is preferred to use SpanFromContext() and test for
37// Nil instead of using this function.
38func SpanOrNoopFromContext(ctx context.Context) Span {
39	if s, ok := ctx.Value(spanKey).(Span); ok {
40		return s
41	}
42	return defaultNoopSpan
43}
44
45// NewContext stores a Zipkin Span into Go's context propagation mechanism.
46func NewContext(ctx context.Context, s Span) context.Context {
47	return context.WithValue(ctx, spanKey, s)
48}
49
50type ctxKey struct{}
51
52var spanKey = ctxKey{}
53