| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
package otelgrpc |
| 5 |
|
| 6 |
import ( |
| 7 |
"context" |
| 8 |
|
| 9 |
"go.opentelemetry.io/otel/propagation" |
| 10 |
"google.golang.org/grpc/metadata" |
| 11 |
) |
| 12 |
|
| 13 |
type metadataSupplier struct { |
| 14 |
metadata metadata.MD |
| 15 |
} |
| 16 |
|
| 17 |
|
| 18 |
var _ propagation.TextMapCarrier = metadataSupplier{} |
| 19 |
|
| 20 |
func (s metadataSupplier) Get(key string) string { |
| 21 |
values := s.metadata.Get(key) |
| 22 |
if len(values) == 0 { |
| 23 |
return "" |
| 24 |
} |
| 25 |
return values[0] |
| 26 |
} |
| 27 |
|
| 28 |
func (s metadataSupplier) Set(key, value string) { |
| 29 |
s.metadata.Set(key, value) |
| 30 |
} |
| 31 |
|
| 32 |
func (s metadataSupplier) Keys() []string { |
| 33 |
out := make([]string, 0, len(s.metadata)) |
| 34 |
for key := range s.metadata { |
| 35 |
out = append(out, key) |
| 36 |
} |
| 37 |
return out |
| 38 |
} |
| 39 |
|
| 40 |
func inject(ctx context.Context, propagators propagation.TextMapPropagator) context.Context { |
| 41 |
md, ok := metadata.FromOutgoingContext(ctx) |
| 42 |
if !ok { |
| 43 |
md = metadata.MD{} |
| 44 |
} |
| 45 |
propagators.Inject(ctx, metadataSupplier{ |
| 46 |
metadata: md, |
| 47 |
}) |
| 48 |
return metadata.NewOutgoingContext(ctx, md) |
| 49 |
} |
| 50 |
|
| 51 |
func extract(ctx context.Context, propagators propagation.TextMapPropagator) context.Context { |
| 52 |
md, ok := metadata.FromIncomingContext(ctx) |
| 53 |
if !ok { |
| 54 |
md = metadata.MD{} |
| 55 |
} |
| 56 |
|
| 57 |
return propagators.Extract(ctx, metadataSupplier{ |
| 58 |
metadata: md, |
| 59 |
}) |
| 60 |
} |