Skip to content

Commit 7225a09

Browse files
committed
add SpanOrNoopFromContext convenience function
1 parent b7a66d0 commit 7225a09

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

context.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import (
44
"context"
55
)
66

7+
var defaultNoopSpan = &noopSpan{}
8+
79
// SpanFromContext retrieves a Zipkin Span from Go's context propagation
810
// mechanism if found. If not found, returns nil.
911
func SpanFromContext(ctx context.Context) Span {
@@ -13,6 +15,19 @@ func SpanFromContext(ctx context.Context) Span {
1315
return nil
1416
}
1517

18+
// SpanOrNoopFromContext retrieves a Zipkin Span from Go's context propagation
19+
// mechanism if found. If not found, returns a noopSpan.
20+
// This function typically is used for modules that want to provide existing
21+
// Zipkin spans with additional data, but can't guarantee that spans are
22+
// properly propagated. It is preferred to use SpanFromContext() and test for
23+
// Nil instead of using this function.
24+
func SpanOrNoopFromContext(ctx context.Context) Span {
25+
if s, ok := ctx.Value(spanKey).(Span); ok {
26+
return s
27+
}
28+
return defaultNoopSpan
29+
}
30+
1631
// NewContext stores a Zipkin Span into Go's context propagation mechanism.
1732
func NewContext(ctx context.Context, s Span) context.Context {
1833
return context.WithValue(ctx, spanKey, s)

context_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package zipkin
2+
3+
import (
4+
"context"
5+
"testing"
6+
)
7+
8+
func TestSpanOrNoopFromContext(t *testing.T) {
9+
var (
10+
ctx = context.Background()
11+
tr, _ = NewTracer(nil, WithLocalEndpoint(nil))
12+
span = tr.StartSpan("test")
13+
)
14+
15+
if want, have := defaultNoopSpan, SpanOrNoopFromContext(ctx); want != have {
16+
t.Errorf("Invalid response want %+v, have %+v", want, have)
17+
}
18+
19+
ctx = NewContext(ctx, span)
20+
21+
if want, have := span, SpanOrNoopFromContext(ctx); want != have {
22+
t.Errorf("Invalid response want %+v, have %+v", want, have)
23+
}
24+
25+
}

0 commit comments

Comments
 (0)