github.com/songzhibin97/gkit@v1.2.13/trace/metadata.go (about)

     1  package trace
     2  
     3  import (
     4  	"context"
     5  
     6  	"github.com/songzhibin97/gkit/internal/metadata"
     7  	"go.opentelemetry.io/otel/propagation"
     8  )
     9  
    10  const serverMark = "x-meta-service-name"
    11  
    12  type Metadata struct {
    13  	Name string
    14  }
    15  
    16  var _ propagation.TextMapPropagator = Metadata{}
    17  
    18  // Inject set cross-cutting concerns from the Context into the carrier.
    19  func (m Metadata) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {
    20  	carrier.Set(serverMark, m.Name)
    21  }
    22  
    23  // Extract reads cross-cutting concerns from the carrier into a Context.
    24  func (m Metadata) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {
    25  	name := carrier.Get(serverMark)
    26  	if name != "" {
    27  		if md, ok := metadata.FromServerContext(ctx); ok {
    28  			md.Set(serverMark, name)
    29  		} else {
    30  			// 设置新的metadata
    31  			md := metadata.NewMetadata()
    32  			md.Set(serverMark, name)
    33  			ctx = metadata.NewServerContext(ctx, md)
    34  		}
    35  	}
    36  	return ctx
    37  }
    38  
    39  // Fields returns the keys who's values are set with Inject.
    40  func (m Metadata) Fields() []string {
    41  	return []string{serverMark}
    42  }