context.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package baggage // import "go.opentelemetry.io/otel/internal/baggage"
  4. import "context"
  5. type baggageContextKeyType int
  6. const baggageKey baggageContextKeyType = iota
  7. // SetHookFunc is a callback called when storing baggage in the context.
  8. type SetHookFunc func(context.Context, List) context.Context
  9. // GetHookFunc is a callback called when getting baggage from the context.
  10. type GetHookFunc func(context.Context, List) List
  11. type baggageState struct {
  12. list List
  13. setHook SetHookFunc
  14. getHook GetHookFunc
  15. }
  16. // ContextWithSetHook returns a copy of parent with hook configured to be
  17. // invoked every time ContextWithBaggage is called.
  18. //
  19. // Passing nil SetHookFunc creates a context with no set hook to call.
  20. func ContextWithSetHook(parent context.Context, hook SetHookFunc) context.Context {
  21. var s baggageState
  22. if v, ok := parent.Value(baggageKey).(baggageState); ok {
  23. s = v
  24. }
  25. s.setHook = hook
  26. return context.WithValue(parent, baggageKey, s)
  27. }
  28. // ContextWithGetHook returns a copy of parent with hook configured to be
  29. // invoked every time FromContext is called.
  30. //
  31. // Passing nil GetHookFunc creates a context with no get hook to call.
  32. func ContextWithGetHook(parent context.Context, hook GetHookFunc) context.Context {
  33. var s baggageState
  34. if v, ok := parent.Value(baggageKey).(baggageState); ok {
  35. s = v
  36. }
  37. s.getHook = hook
  38. return context.WithValue(parent, baggageKey, s)
  39. }
  40. // ContextWithList returns a copy of parent with baggage. Passing nil list
  41. // returns a context without any baggage.
  42. func ContextWithList(parent context.Context, list List) context.Context {
  43. var s baggageState
  44. if v, ok := parent.Value(baggageKey).(baggageState); ok {
  45. s = v
  46. }
  47. s.list = list
  48. ctx := context.WithValue(parent, baggageKey, s)
  49. if s.setHook != nil {
  50. ctx = s.setHook(ctx, list)
  51. }
  52. return ctx
  53. }
  54. // ListFromContext returns the baggage contained in ctx.
  55. func ListFromContext(ctx context.Context) List {
  56. switch v := ctx.Value(baggageKey).(type) {
  57. case baggageState:
  58. if v.getHook != nil {
  59. return v.getHook(ctx, v.list)
  60. }
  61. return v.list
  62. default:
  63. return nil
  64. }
  65. }