baggage.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright The OpenTelemetry Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package propagation // import "go.opentelemetry.io/otel/propagation"
  15. import (
  16. "context"
  17. "go.opentelemetry.io/otel/baggage"
  18. )
  19. const baggageHeader = "baggage"
  20. // Baggage is a propagator that supports the W3C Baggage format.
  21. //
  22. // This propagates user-defined baggage associated with a trace. The complete
  23. // specification is defined at https://w3c.github.io/baggage/.
  24. type Baggage struct{}
  25. var _ TextMapPropagator = Baggage{}
  26. // Inject sets baggage key-values from ctx into the carrier.
  27. func (b Baggage) Inject(ctx context.Context, carrier TextMapCarrier) {
  28. bStr := baggage.FromContext(ctx).String()
  29. if bStr != "" {
  30. carrier.Set(baggageHeader, bStr)
  31. }
  32. }
  33. // Extract returns a copy of parent with the baggage from the carrier added.
  34. func (b Baggage) Extract(parent context.Context, carrier TextMapCarrier) context.Context {
  35. bStr := carrier.Get(baggageHeader)
  36. if bStr == "" {
  37. return parent
  38. }
  39. bag, err := baggage.Parse(bStr)
  40. if err != nil {
  41. return parent
  42. }
  43. return baggage.ContextWithBaggage(parent, bag)
  44. }
  45. // Fields returns the keys who's values are set with Inject.
  46. func (b Baggage) Fields() []string {
  47. return []string{baggageHeader}
  48. }