-
Notifications
You must be signed in to change notification settings - Fork 0
/
metadata.go
45 lines (36 loc) · 1.13 KB
/
metadata.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package tracing
import (
"context"
"github.com/go-kratos/kratos/v2"
"github.com/go-kratos/kratos/v2/metadata"
"go.opentelemetry.io/otel/propagation"
)
const serviceHeader = "x-md-service-name"
// Metadata is tracing metadata propagator
type Metadata struct{}
var _ propagation.TextMapPropagator = Metadata{}
// Inject sets metadata key-values from ctx into the carrier.
func (b Metadata) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {
app, ok := kratos.FromContext(ctx)
if ok {
carrier.Set(serviceHeader, app.Name())
}
}
// Extract returns a copy of parent with the metadata from the carrier added.
func (b Metadata) Extract(parent context.Context, carrier propagation.TextMapCarrier) context.Context {
name := carrier.Get(serviceHeader)
if name != "" {
if md, ok := metadata.FromServerContext(parent); ok {
md.Set(serviceHeader, name)
} else {
md := metadata.New()
md.Set(serviceHeader, name)
parent = metadata.NewServerContext(parent, md)
}
}
return parent
}
// Fields returns the keys who's values are set with Inject.
func (b Metadata) Fields() []string {
return []string{serviceHeader}
}