| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
package otelhttptrace |
| 7 |
|
| 8 |
import ( |
| 9 |
"context" |
| 10 |
"net/http" |
| 11 |
|
| 12 |
"go.opentelemetry.io/otel" |
| 13 |
"go.opentelemetry.io/otel/attribute" |
| 14 |
"go.opentelemetry.io/otel/baggage" |
| 15 |
"go.opentelemetry.io/otel/propagation" |
| 16 |
"go.opentelemetry.io/otel/trace" |
| 17 |
|
| 18 |
"go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace/internal/semconv" |
| 19 |
) |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
type Option interface { |
| 24 |
apply(*config) |
| 25 |
} |
| 26 |
|
| 27 |
type optionFunc func(*config) |
| 28 |
|
| 29 |
func (o optionFunc) apply(c *config) { |
| 30 |
o(c) |
| 31 |
} |
| 32 |
|
| 33 |
type config struct { |
| 34 |
propagators propagation.TextMapPropagator |
| 35 |
} |
| 36 |
|
| 37 |
func newConfig(opts []Option) *config { |
| 38 |
c := &config{propagators: otel.GetTextMapPropagator()} |
| 39 |
for _, o := range opts { |
| 40 |
o.apply(c) |
| 41 |
} |
| 42 |
return c |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
func WithPropagators(props propagation.TextMapPropagator) Option { |
| 47 |
return optionFunc(func(c *config) { |
| 48 |
if props != nil { |
| 49 |
c.propagators = props |
| 50 |
} |
| 51 |
}) |
| 52 |
} |
| 53 |
|
| 54 |
|
| 55 |
func Extract(ctx context.Context, req *http.Request, opts ...Option) ([]attribute.KeyValue, baggage.Baggage, trace.SpanContext) { |
| 56 |
c := newConfig(opts) |
| 57 |
ctx = c.propagators.Extract(ctx, propagation.HeaderCarrier(req.Header)) |
| 58 |
|
| 59 |
semconvSrv := semconv.NewHTTPServer(nil) |
| 60 |
|
| 61 |
attrs := append(semconvSrv.RequestTraceAttrs("", req, semconv.RequestTraceAttrsOpts{}), semconvSrv.NetworkTransportAttr("tcp")...) |
| 62 |
attrs = append(attrs, semconvSrv.ResponseTraceAttrs(semconv.ResponseTelemetry{ |
| 63 |
ReadBytes: req.ContentLength, |
| 64 |
})...) |
| 65 |
|
| 66 |
return attrs, baggage.FromContext(ctx), trace.SpanContextFromContext(ctx) |
| 67 |
} |
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
func Inject(ctx context.Context, req *http.Request, opts ...Option) { |
| 72 |
c := newConfig(opts) |
| 73 |
c.propagators.Inject(ctx, propagation.HeaderCarrier(req.Header)) |
| 74 |
} |