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