github.com/pinpoint-apm/pinpoint-go-agent@v1.4.1-0.20240110120318-a50c2eb18c8c/context.go (about)

     1  package pinpoint
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  )
     7  
     8  const contextKey = "pinpoint.spanTracer"
     9  
    10  // NewContext returns a new Context that contains the given Tracer.
    11  func NewContext(ctx context.Context, tracer Tracer) context.Context {
    12  	if ctx == nil {
    13  		ctx = context.Background()
    14  	}
    15  	return context.WithValue(ctx, contextKey, tracer)
    16  }
    17  
    18  // FromContext returns the Tracer from the context. If not present, NoopTracer is returned.
    19  func FromContext(ctx context.Context) Tracer {
    20  	if ctx == nil {
    21  		return NoopTracer()
    22  	}
    23  
    24  	if v := ctx.Value(contextKey); v != nil {
    25  		tracer, ok := v.(Tracer)
    26  		if !ok {
    27  			return NoopTracer()
    28  		}
    29  		return tracer
    30  	} else {
    31  		return NoopTracer()
    32  	}
    33  }
    34  
    35  // RequestWithTracerContext returns the request that has a Context carrying the given Tracer.
    36  func RequestWithTracerContext(req *http.Request, tracer Tracer) *http.Request {
    37  	if req != nil {
    38  		ctx := NewContext(req.Context(), tracer)
    39  		return req.WithContext(ctx)
    40  	} else {
    41  		return req
    42  	}
    43  }
    44  
    45  // TracerFromRequestContext returns the Tracer from the request's context. If not present, NoopTracer is returned.
    46  func TracerFromRequestContext(req *http.Request) Tracer {
    47  	if req != nil {
    48  		return FromContext(req.Context())
    49  	}
    50  	return NoopTracer()
    51  }