github.com/wangyougui/gf/v2@v2.6.5/net/gtrace/gtrace_baggage.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  	"context"
    11  
    12  	"go.opentelemetry.io/otel/baggage"
    13  
    14  	"github.com/wangyougui/gf/v2/container/gmap"
    15  	"github.com/wangyougui/gf/v2/container/gvar"
    16  	"github.com/wangyougui/gf/v2/util/gconv"
    17  )
    18  
    19  // Baggage holds the data through all tracing spans.
    20  type Baggage struct {
    21  	ctx context.Context
    22  }
    23  
    24  // NewBaggage creates and returns a new Baggage object from given tracing context.
    25  func NewBaggage(ctx context.Context) *Baggage {
    26  	if ctx == nil {
    27  		ctx = context.Background()
    28  	}
    29  	return &Baggage{
    30  		ctx: ctx,
    31  	}
    32  }
    33  
    34  // Ctx returns the context that Baggage holds.
    35  func (b *Baggage) Ctx() context.Context {
    36  	return b.ctx
    37  }
    38  
    39  // SetValue is a convenient function for adding one key-value pair to baggage.
    40  // Note that it uses attribute.Any to set the key-value pair.
    41  func (b *Baggage) SetValue(key string, value interface{}) context.Context {
    42  	member, _ := baggage.NewMember(key, gconv.String(value))
    43  	bag, _ := baggage.New(member)
    44  	b.ctx = baggage.ContextWithBaggage(b.ctx, bag)
    45  	return b.ctx
    46  }
    47  
    48  // SetMap is a convenient function for adding map key-value pairs to baggage.
    49  // Note that it uses attribute.Any to set the key-value pair.
    50  func (b *Baggage) SetMap(data map[string]interface{}) context.Context {
    51  	members := make([]baggage.Member, 0)
    52  	for k, v := range data {
    53  		member, _ := baggage.NewMember(k, gconv.String(v))
    54  		members = append(members, member)
    55  	}
    56  	bag, _ := baggage.New(members...)
    57  	b.ctx = baggage.ContextWithBaggage(b.ctx, bag)
    58  	return b.ctx
    59  }
    60  
    61  // GetMap retrieves and returns the baggage values as map.
    62  func (b *Baggage) GetMap() *gmap.StrAnyMap {
    63  	m := gmap.NewStrAnyMap()
    64  	members := baggage.FromContext(b.ctx).Members()
    65  	for i := range members {
    66  		m.Set(members[i].Key(), members[i].Value())
    67  	}
    68  	return m
    69  }
    70  
    71  // GetVar retrieves value and returns a *gvar.Var for specified key from baggage.
    72  func (b *Baggage) GetVar(key string) *gvar.Var {
    73  	value := baggage.FromContext(b.ctx).Member(key).Value()
    74  	return gvar.New(value)
    75  }