spancontext.go 994 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package spancontext
  2. import (
  3. "context"
  4. opentracing "github.com/opentracing/opentracing-go"
  5. )
  6. func WithContext(ctx context.Context, sctx opentracing.SpanContext) context.Context {
  7. return context.WithValue(ctx, "span_context", sctx)
  8. }
  9. func FromContext(ctx context.Context) opentracing.SpanContext {
  10. sctx, ok := ctx.Value("span_context").(opentracing.SpanContext)
  11. if ok {
  12. return sctx
  13. }
  14. return nil
  15. }
  16. func StartSpan(ctx context.Context, name string) (context.Context, opentracing.Span) {
  17. tracer := opentracing.GlobalTracer()
  18. sctx := FromContext(ctx)
  19. var sp opentracing.Span
  20. if sctx != nil {
  21. sp = tracer.StartSpan(
  22. name,
  23. opentracing.ChildOf(sctx))
  24. } else {
  25. sp = tracer.StartSpan(name)
  26. }
  27. nctx := context.WithValue(ctx, "span_context", sp.Context())
  28. return nctx, sp
  29. }
  30. func StartSpanFrom(name string, sctx opentracing.SpanContext) opentracing.Span {
  31. tracer := opentracing.GlobalTracer()
  32. sp := tracer.StartSpan(
  33. name,
  34. opentracing.ChildOf(sctx))
  35. return sp
  36. }