start_time_context.go raw

   1  // Copyright The OpenTelemetry Authors
   2  // SPDX-License-Identifier: Apache-2.0
   3  
   4  package otelhttp // import "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
   5  
   6  import (
   7  	"context"
   8  	"time"
   9  )
  10  
  11  type startTimeContextKeyType int
  12  
  13  const startTimeContextKey startTimeContextKeyType = 0
  14  
  15  // ContextWithStartTime returns a new context with the provided start time. The
  16  // start time will be used for metrics and traces emitted by the
  17  // instrumentation. Only one labeller can be injected into the context.
  18  // Injecting it multiple times will override the previous calls.
  19  func ContextWithStartTime(parent context.Context, start time.Time) context.Context {
  20  	return context.WithValue(parent, startTimeContextKey, start)
  21  }
  22  
  23  // StartTimeFromContext retrieves a time.Time from the provided context if one
  24  // is available. If no start time was found in the provided context, a new,
  25  // zero start time is returned and the second return value is false.
  26  func StartTimeFromContext(ctx context.Context) time.Time {
  27  	t, _ := ctx.Value(startTimeContextKey).(time.Time)
  28  	return t
  29  }
  30