Debian Codegraph @

instrumentation/net/http/httptrace/otelhttptrace/httptrace.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package otelhttptrace provides instrumentation for the [net/http/httptrace]
5 // package.
6 package otelhttptrace // import "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/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 // Option allows configuration of the httptrace Extract()
22 // and Inject() functions.
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 // WithPropagators sets the propagators to use for Extraction and Injection.
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 // Extract returns the Attributes, Context Entries, and SpanContext that were encoded by Inject.
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 // Inject sets attributes, context entries, and span context from ctx into
70 // the request.
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 }