github.com/wangyougui/gf/v2@v2.6.5/net/gtrace/gtrace_carrier.go (about)

     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/wangyougui/gf.
     6  
     7  package gtrace
     8  
     9  import (
    10  	"github.com/wangyougui/gf/v2/internal/json"
    11  	"github.com/wangyougui/gf/v2/util/gconv"
    12  )
    13  
    14  // Carrier is the storage medium used by a TextMapPropagator.
    15  type Carrier map[string]interface{}
    16  
    17  // NewCarrier creates and returns a Carrier.
    18  func NewCarrier(data ...map[string]interface{}) Carrier {
    19  	if len(data) > 0 && data[0] != nil {
    20  		return data[0]
    21  	}
    22  	return make(map[string]interface{})
    23  }
    24  
    25  // Get returns the value associated with the passed key.
    26  func (c Carrier) Get(k string) string {
    27  	return gconv.String(c[k])
    28  }
    29  
    30  // Set stores the key-value pair.
    31  func (c Carrier) Set(k, v string) {
    32  	c[k] = v
    33  }
    34  
    35  // Keys lists the keys stored in this carrier.
    36  func (c Carrier) Keys() []string {
    37  	keys := make([]string, 0, len(c))
    38  	for k := range c {
    39  		keys = append(keys, k)
    40  	}
    41  	return keys
    42  }
    43  
    44  // MustMarshal .returns the JSON encoding of c
    45  func (c Carrier) MustMarshal() []byte {
    46  	b, err := json.Marshal(c)
    47  	if err != nil {
    48  		panic(err)
    49  	}
    50  	return b
    51  }
    52  
    53  // String converts and returns current Carrier as string.
    54  func (c Carrier) String() string {
    55  	return string(c.MustMarshal())
    56  }
    57  
    58  // UnmarshalJSON implements interface UnmarshalJSON for package json.
    59  func (c Carrier) UnmarshalJSON(b []byte) error {
    60  	carrier := NewCarrier(nil)
    61  	return json.UnmarshalUseNumber(b, carrier)
    62  }