gtrace_baggage.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gtrace
  7. import (
  8. "context"
  9. "github.com/gogf/gf/container/gmap"
  10. "github.com/gogf/gf/container/gvar"
  11. "github.com/gogf/gf/util/gconv"
  12. "go.opentelemetry.io/otel/baggage"
  13. )
  14. // Baggage holds the data through all tracing spans.
  15. type Baggage struct {
  16. ctx context.Context
  17. }
  18. // NewBaggage creates and returns a new Baggage object from given tracing context.
  19. func NewBaggage(ctx context.Context) *Baggage {
  20. if ctx == nil {
  21. ctx = context.Background()
  22. }
  23. return &Baggage{
  24. ctx: ctx,
  25. }
  26. }
  27. // Ctx returns the context that Baggage holds.
  28. func (b *Baggage) Ctx() context.Context {
  29. return b.ctx
  30. }
  31. // SetValue is a convenient function for adding one key-value pair to baggage.
  32. // Note that it uses attribute.Any to set the key-value pair.
  33. func (b *Baggage) SetValue(key string, value interface{}) context.Context {
  34. member, _ := baggage.NewMember(key, gconv.String(value))
  35. bag, _ := baggage.New(member)
  36. b.ctx = baggage.ContextWithBaggage(b.ctx, bag)
  37. return b.ctx
  38. }
  39. // SetMap is a convenient function for adding map key-value pairs to baggage.
  40. // Note that it uses attribute.Any to set the key-value pair.
  41. func (b *Baggage) SetMap(data map[string]interface{}) context.Context {
  42. members := make([]baggage.Member, 0)
  43. for k, v := range data {
  44. member, _ := baggage.NewMember(k, gconv.String(v))
  45. members = append(members, member)
  46. }
  47. bag, _ := baggage.New(members...)
  48. b.ctx = baggage.ContextWithBaggage(b.ctx, bag)
  49. return b.ctx
  50. }
  51. // GetMap retrieves and returns the baggage values as map.
  52. func (b *Baggage) GetMap() *gmap.StrAnyMap {
  53. m := gmap.NewStrAnyMap()
  54. members := baggage.FromContext(b.ctx).Members()
  55. for i := range members {
  56. m.Set(members[i].Key(), members[i].Value())
  57. }
  58. return m
  59. }
  60. // GetVar retrieves value and returns a *gvar.Var for specified key from baggage.
  61. func (b *Baggage) GetVar(key string) *gvar.Var {
  62. value := baggage.FromContext(b.ctx).Member(key).Value()
  63. return gvar.New(value)
  64. }