-
Notifications
You must be signed in to change notification settings - Fork 3
/
metadata.go
45 lines (36 loc) · 1.12 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 otel
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 otel 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}
}