context.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2022 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. package zipkin
  15. import (
  16. "context"
  17. "github.com/openzipkin/zipkin-go/model"
  18. )
  19. var defaultNoopSpan = &noopSpan{}
  20. // SpanFromContext retrieves a Zipkin Span from Go's context propagation
  21. // mechanism if found. If not found, returns nil.
  22. func SpanFromContext(ctx context.Context) Span {
  23. if s, ok := ctx.Value(spanKey).(Span); ok {
  24. return s
  25. }
  26. return nil
  27. }
  28. // SpanOrNoopFromContext retrieves a Zipkin Span from Go's context propagation
  29. // mechanism if found. If not found, returns a noopSpan.
  30. // This function typically is used for modules that want to provide existing
  31. // Zipkin spans with additional data, but can't guarantee that spans are
  32. // properly propagated. It is preferred to use SpanFromContext() and test for
  33. // Nil instead of using this function.
  34. func SpanOrNoopFromContext(ctx context.Context) Span {
  35. if s, ok := ctx.Value(spanKey).(Span); ok {
  36. return s
  37. }
  38. return defaultNoopSpan
  39. }
  40. // NewContext stores a Zipkin Span into Go's context propagation mechanism.
  41. func NewContext(ctx context.Context, s Span) context.Context {
  42. return context.WithValue(ctx, spanKey, s)
  43. }
  44. // BaggageFromContext takes a context and returns access to BaggageFields if
  45. // available. Returns nil if there are no BaggageFields found in context.
  46. func BaggageFromContext(ctx context.Context) model.BaggageFields {
  47. if span := SpanFromContext(ctx); span != nil {
  48. return span.Context().Baggage
  49. }
  50. return nil
  51. }
  52. type ctxKey struct{}
  53. var spanKey = ctxKey{}