github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/swarm/spancontext/spancontext.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 19:16:44</date>
    10  //</624450118162059264>
    11  
    12  package spancontext
    13  
    14  import (
    15  	"context"
    16  
    17  	opentracing "github.com/opentracing/opentracing-go"
    18  )
    19  
    20  func WithContext(ctx context.Context, sctx opentracing.SpanContext) context.Context {
    21  	return context.WithValue(ctx, "span_context", sctx)
    22  }
    23  
    24  func FromContext(ctx context.Context) opentracing.SpanContext {
    25  	sctx, ok := ctx.Value("span_context").(opentracing.SpanContext)
    26  	if ok {
    27  		return sctx
    28  	}
    29  
    30  	return nil
    31  }
    32  
    33  func StartSpan(ctx context.Context, name string) (context.Context, opentracing.Span) {
    34  	tracer := opentracing.GlobalTracer()
    35  
    36  	sctx := FromContext(ctx)
    37  
    38  	var sp opentracing.Span
    39  	if sctx != nil {
    40  		sp = tracer.StartSpan(
    41  			name,
    42  			opentracing.ChildOf(sctx))
    43  	} else {
    44  		sp = tracer.StartSpan(name)
    45  	}
    46  
    47  	nctx := context.WithValue(ctx, "span_context", sp.Context())
    48  
    49  	return nctx, sp
    50  }
    51  
    52  func StartSpanFrom(name string, sctx opentracing.SpanContext) opentracing.Span {
    53  	tracer := opentracing.GlobalTracer()
    54  
    55  	sp := tracer.StartSpan(
    56  		name,
    57  		opentracing.ChildOf(sctx))
    58  
    59  	return sp
    60  }
    61