gtrace_carrier.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. "github.com/gogf/gf/internal/json"
  9. "github.com/gogf/gf/util/gconv"
  10. )
  11. // Carrier is the storage medium used by a TextMapPropagator.
  12. type Carrier map[string]interface{}
  13. func NewCarrier(data ...map[string]interface{}) Carrier {
  14. if len(data) > 0 && data[0] != nil {
  15. return data[0]
  16. } else {
  17. return make(map[string]interface{})
  18. }
  19. }
  20. // Get returns the value associated with the passed key.
  21. func (c Carrier) Get(k string) string {
  22. return gconv.String(c[k])
  23. }
  24. // Set stores the key-value pair.
  25. func (c Carrier) Set(k, v string) {
  26. c[k] = v
  27. }
  28. // Keys lists the keys stored in this carrier.
  29. func (c Carrier) Keys() []string {
  30. keys := make([]string, 0, len(c))
  31. for k := range c {
  32. keys = append(keys, k)
  33. }
  34. return keys
  35. }
  36. func (c Carrier) MustMarshal() []byte {
  37. b, err := json.Marshal(c)
  38. if err != nil {
  39. panic(err)
  40. }
  41. return b
  42. }
  43. func (c Carrier) String() string {
  44. return string(c.MustMarshal())
  45. }
  46. func (c Carrier) UnmarshalJSON(b []byte) error {
  47. carrier := NewCarrier(nil)
  48. return json.UnmarshalUseNumber(b, carrier)
  49. }