gtrace_carrier.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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/v2/internal/json"
  9. "github.com/gogf/gf/v2/util/gconv"
  10. )
  11. // Carrier is the storage medium used by a TextMapPropagator.
  12. type Carrier map[string]interface{}
  13. // NewCarrier creates and returns a Carrier.
  14. func NewCarrier(data ...map[string]interface{}) Carrier {
  15. if len(data) > 0 && data[0] != nil {
  16. return data[0]
  17. }
  18. return make(map[string]interface{})
  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. // MustMarshal .returns the JSON encoding of c
  37. func (c Carrier) MustMarshal() []byte {
  38. b, err := json.Marshal(c)
  39. if err != nil {
  40. panic(err)
  41. }
  42. return b
  43. }
  44. // String converts and returns current Carrier as string.
  45. func (c Carrier) String() string {
  46. return string(c.MustMarshal())
  47. }
  48. // UnmarshalJSON implements interface UnmarshalJSON for package json.
  49. func (c Carrier) UnmarshalJSON(b []byte) error {
  50. carrier := NewCarrier(nil)
  51. return json.UnmarshalUseNumber(b, carrier)
  52. }