Go app framework
This commit is contained in:
54
pkg/otel/ctx.go
Normal file
54
pkg/otel/ctx.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package otel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
type otelCtxKey uint8
|
||||
|
||||
const (
|
||||
ctxKeyTracer otelCtxKey = iota
|
||||
ctxKeyMeter
|
||||
)
|
||||
|
||||
func MustTracerFromCtx(ctx context.Context) trace.Tracer {
|
||||
ctxData := ctx.Value(ctxKeyTracer)
|
||||
if ctxData == nil {
|
||||
panic(errors.New("no tracer found in context"))
|
||||
}
|
||||
|
||||
tracer, ok := ctxData.(trace.Tracer)
|
||||
if !ok {
|
||||
panic(errors.New("invalid tracer found in context"))
|
||||
}
|
||||
|
||||
return tracer
|
||||
}
|
||||
|
||||
func AddTracerToCtx(ctx context.Context, tracer trace.Tracer) context.Context {
|
||||
ctx = context.WithValue(ctx, ctxKeyTracer, tracer)
|
||||
return ctx
|
||||
}
|
||||
|
||||
func MustMeterFromCtx(ctx context.Context) metric.Meter {
|
||||
ctxData := ctx.Value(ctxKeyMeter)
|
||||
if ctxData == nil {
|
||||
panic(errors.New("no meter found in context"))
|
||||
}
|
||||
|
||||
meter, ok := ctxData.(metric.Meter)
|
||||
if !ok {
|
||||
panic(errors.New("invalid meter found in context"))
|
||||
}
|
||||
|
||||
return meter
|
||||
}
|
||||
|
||||
func AddMeterToCtx(ctx context.Context, meter metric.Meter) context.Context {
|
||||
ctx = context.WithValue(ctx, ctxKeyMeter, meter)
|
||||
return ctx
|
||||
}
|
Reference in New Issue
Block a user