baggage.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package propagation // import "go.opentelemetry.io/otel/propagation"
  4. import (
  5. "context"
  6. "go.opentelemetry.io/otel/baggage"
  7. )
  8. const baggageHeader = "baggage"
  9. // Baggage is a propagator that supports the W3C Baggage format.
  10. //
  11. // This propagates user-defined baggage associated with a trace. The complete
  12. // specification is defined at https://www.w3.org/TR/baggage/.
  13. type Baggage struct{}
  14. var _ TextMapPropagator = Baggage{}
  15. // Inject sets baggage key-values from ctx into the carrier.
  16. func (b Baggage) Inject(ctx context.Context, carrier TextMapCarrier) {
  17. bStr := baggage.FromContext(ctx).String()
  18. if bStr != "" {
  19. carrier.Set(baggageHeader, bStr)
  20. }
  21. }
  22. // Extract returns a copy of parent with the baggage from the carrier added.
  23. func (b Baggage) Extract(parent context.Context, carrier TextMapCarrier) context.Context {
  24. bStr := carrier.Get(baggageHeader)
  25. if bStr == "" {
  26. return parent
  27. }
  28. bag, err := baggage.Parse(bStr)
  29. if err != nil {
  30. return parent
  31. }
  32. return baggage.ContextWithBaggage(parent, bag)
  33. }
  34. // Fields returns the keys who's values are set with Inject.
  35. func (b Baggage) Fields() []string {
  36. return []string{baggageHeader}
  37. }