CodeSampleX

Exemplo

go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0: WithPropagators

Amostra verificada para golang go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0: WithPropagators. O contrato rodou em go 1.26 · linux…

sha256:910a587d7f3819190266bd8538ce21966380453088d650e8e70d3a40fec0f497

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-07

Caso

HOW
Objetivo
verify otelhttp.WithPropagators in pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.68.0
Pacotes
Símbolos
  • otelhttp.WithPropagators
Ambiente
go 1.26.6
Criado
2026-09-07T05:37:48Z

Contrato

  1. otelhttp.WithPropagators configures TextMapPropagator for HTTP handler inbound trace and baggage extraction
  2. otelhttp.WithPropagators configures TextMapPropagator for HTTP transport outbound trace and baggage injection
  3. otelhttp.WithPropagators with nil propagator preserves default propagator without panic

Arquivos

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.go

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify otelhttp.WithPropagators in pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.68.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.68.0
Demonstrate these symbols/APIs:
  - otelhttp.WithPropagators

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:a3d92d1b72d7421e3792dcb83a7cd6d05fe2eb3e29dd8996e0577d8ad278916d","contract":["otelhttp.WithPropagators configures TextMapPropagator for HTTP handler inbound trace and baggage extraction","otelhttp.WithPropagators configures TextMapPropagator for HTTP transport outbound trace and baggage injection","otelhttp.WithPropagators with nil propagator preserves default propagator without panic"],"goal":"verify otelhttp.WithPropagators in pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.68.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.68.0"],"schemaVersion":1,"symbols":["otelhttp.WithPropagators"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","packageManagerVersion":"1.26.6","runtime":"go","runtimeVersion":"1.26.6","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.68.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.68.0","symbols":["otelhttp.WithPropagators"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require (
	go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0
	go.opentelemetry.io/otel v1.43.0
	go.opentelemetry.io/otel/trace v1.43.0
)

require (
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/felixge/httpsnoop v1.0.4 // indirect
	github.com/go-logr/logr v1.4.3 // indirect
	github.com/go-logr/stdr v1.2.2 // indirect
	go.opentelemetry.io/auto/sdk v1.2.1 // indirect
	go.opentelemetry.io/otel/metric v1.43.0 // indirect
)
go.sum
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo=
go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
go.opentelemetry.io/otel/sdk/metric v1.43.0 h1:S88dyqXjJkuBNLeMcVPRFXpRw2fuwdvfCGLEo89fDkw=
go.opentelemetry.io/otel/sdk/metric v1.43.0/go.mod h1:C/RJtwSEJ5hzTiUz5pXF1kILHStzb9zFlIEe85bhj6A=
go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
main.go
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"

	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/otel/propagation"
)

func main() {
	propagator := propagation.NewCompositeTextMapPropagator(
		propagation.TraceContext{},
		propagation.Baggage{},
	)

	// Configure HTTP handler with custom propagators
	handler := otelhttp.NewHandler(
		http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusOK)
			_, _ = w.Write([]byte("propagator configured"))
		}),
		"example-operation",
		otelhttp.WithPropagators(propagator),
	)

	// Configure HTTP transport with custom propagators
	transport := otelhttp.NewTransport(
		http.DefaultTransport,
		otelhttp.WithPropagators(propagator),
	)

	req := httptest.NewRequest(http.MethodGet, "http://localhost/example", nil)
	rec := httptest.NewRecorder()
	handler.ServeHTTP(rec, req)

	_ = transport
	_ = context.Background()
	fmt.Println("otelhttp.WithPropagators configured successfully")
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify otelhttp.WithPropagators in pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.68.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.68.0"
  ],
  "symbols": [
    "otelhttp.WithPropagators"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"

	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/otel/baggage"
	"go.opentelemetry.io/otel/propagation"
	"go.opentelemetry.io/otel/trace"
)

type contextKey string

const (
	testTraceKey   contextKey = "test-trace-id"
	testBaggageKey contextKey = "test-baggage-key"
)

// testPropagator demonstrates a custom TextMapPropagator injected/extracted by otelhttp.
type testPropagator struct{}

func (p testPropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {
	if val, ok := ctx.Value(testTraceKey).(string); ok && val != "" {
		carrier.Set("x-test-trace", val)
	}
	if val, ok := ctx.Value(testBaggageKey).(string); ok && val != "" {
		carrier.Set("x-test-baggage", val)
	}
}

func (p testPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {
	if val := carrier.Get("x-test-trace"); val != "" {
		ctx = context.WithValue(ctx, testTraceKey, val)
	}
	if val := carrier.Get("x-test-baggage"); val != "" {
		ctx = context.WithValue(ctx, testBaggageKey, val)
	}
	return ctx
}

func (p testPropagator) Fields() []string {
	return []string{"x-test-trace", "x-test-baggage"}
}

type roundTripperFunc func(*http.Request) (*http.Response, error)

func (f roundTripperFunc) RoundTrip(r *http.Request) (*http.Response, error) {
	return f(r)
}

func main() {
	if err := runContractTests(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract test failure: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All contract assertions passed successfully.")
}

func runContractTests() error {
	compositePropagator := propagation.NewCompositeTextMapPropagator(
		propagation.TraceContext{},
		propagation.Baggage{},
		testPropagator{},
	)

	// Assertion 1: otelhttp.WithPropagators configures TextMapPropagator for HTTP handler inbound trace and baggage extraction
	if err := testHandlerInbound(compositePropagator); err != nil {
		return fmt.Errorf("handler inbound test failed: %w", err)
	}

	// Assertion 2: otelhttp.WithPropagators configures TextMapPropagator for HTTP transport outbound trace and baggage injection
	if err := testTransportOutbound(compositePropagator); err != nil {
		return fmt.Errorf("transport outbound test failed: %w", err)
	}

	// Assertion 3: otelhttp.WithPropagators with nil propagator preserves default propagator without panic
	if err := testNilPropagator(); err != nil {
		return fmt.Errorf("nil propagator test failed: %w", err)
	}

	return nil
}

func testHandlerInbound(prop propagation.TextMapPropagator) error {
	var extractedTrace string
	var extractedBaggage string
	var extractedW3CTraceID string
	var extractedW3CBaggage string

	innerHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if v, ok := r.Context().Value(testTraceKey).(string); ok {
			extractedTrace = v
		}
		if v, ok := r.Context().Value(testBaggageKey).(string); ok {
			extractedBaggage = v
		}

		sc := trace.SpanContextFromContext(r.Context())
		if sc.IsValid() {
			extractedW3CTraceID = sc.TraceID().String()
		}

		bag := baggage.FromContext(r.Context())
		extractedW3CBaggage = bag.Member("role").Value()

		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("OK"))
	})

	handler := otelhttp.NewHandler(
		innerHandler,
		"test-handler-op",
		otelhttp.WithPropagators(prop),
	)

	req := httptest.NewRequest(http.MethodGet, "http://localhost/test", nil)
	req.Header.Set("x-test-trace", "trace-abc-123")
	req.Header.Set("x-test-baggage", "baggage-xyz-789")
	req.Header.Set("traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
	req.Header.Set("baggage", "role=admin")

	rec := httptest.NewRecorder()
	handler.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		return fmt.Errorf("handler returned status %d, want 200", rec.Code)
	}
	if extractedTrace != "trace-abc-123" {
		return fmt.Errorf("extracted custom trace mismatch: got %q, want %q", extractedTrace, "trace-abc-123")
	}
	if extractedBaggage != "baggage-xyz-789" {
		return fmt.Errorf("extracted custom baggage mismatch: got %q, want %q", extractedBaggage, "baggage-xyz-789")
	}
	if extractedW3CTraceID != "4bf92f3577b34da6a3ce929d0e0e4736" {
		return fmt.Errorf("extracted W3C trace ID mismatch: got %q, want %q", extractedW3CTraceID, "4bf92f3577b34da6a3ce929d0e0e4736")
	}
	if extractedW3CBaggage != "admin" {
		return fmt.Errorf("extracted W3C baggage mismatch: got %q, want %q", extractedW3CBaggage, "admin")
	}

	return nil
}

func testTransportOutbound(prop propagation.TextMapPropagator) error {
	var capturedCustomTrace string
	var capturedCustomBaggage string
	var capturedW3CBaggage string

	mockRT := roundTripperFunc(func(r *http.Request) (*http.Response, error) {
		capturedCustomTrace = r.Header.Get("x-test-trace")
		capturedCustomBaggage = r.Header.Get("x-test-baggage")
		capturedW3CBaggage = r.Header.Get("baggage")
		return &http.Response{
			StatusCode: http.StatusOK,
			Header:     make(http.Header),
			Body:       io.NopCloser(bytes.NewReader([]byte("transport-ok"))),
		}, nil
	})

	transport := otelhttp.NewTransport(
		mockRT,
		otelhttp.WithPropagators(prop),
	)

	ctx := context.Background()
	ctx = context.WithValue(ctx, testTraceKey, "out-trace-555")
	ctx = context.WithValue(ctx, testBaggageKey, "out-baggage-666")
	bMember, err := baggage.NewMember("tenant", "acme")
	if err != nil {
		return fmt.Errorf("failed to create baggage member: %w", err)
	}
	bag, err := baggage.New(bMember)
	if err != nil {
		return fmt.Errorf("failed to create baggage: %w", err)
	}
	ctx = baggage.ContextWithBaggage(ctx, bag)

	outReq, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost/outbound", nil)
	if err != nil {
		return fmt.Errorf("failed to create outbound request: %w", err)
	}

	resp, err := transport.RoundTrip(outReq)
	if err != nil {
		return fmt.Errorf("transport RoundTrip failed: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("transport returned status %d, want 200", resp.StatusCode)
	}
	if capturedCustomTrace != "out-trace-555" {
		return fmt.Errorf("captured custom trace mismatch: got %q, want %q", capturedCustomTrace, "out-trace-555")
	}
	if capturedCustomBaggage != "out-baggage-666" {
		return fmt.Errorf("captured custom baggage mismatch: got %q, want %q", capturedCustomBaggage, "out-baggage-666")
	}
	if capturedW3CBaggage != "tenant=acme" {
		return fmt.Errorf("captured W3C baggage mismatch: got %q, want %q", capturedW3CBaggage, "tenant=acme")
	}

	return nil
}

func testNilPropagator() error {
	nilPropOpt := otelhttp.WithPropagators(nil)
	if nilPropOpt == nil {
		return fmt.Errorf("WithPropagators(nil) returned nil option")
	}

	var defaultHandlerInvoked bool
	defaultInner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defaultHandlerInvoked = true
		w.WriteHeader(http.StatusOK)
	})

	nilHandler := otelhttp.NewHandler(defaultInner, "default-op", nilPropOpt)
	nilReq := httptest.NewRequest(http.MethodGet, "http://localhost/nil-test", nil)
	nilRec := httptest.NewRecorder()
	nilHandler.ServeHTTP(nilRec, nilReq)

	if !defaultHandlerInvoked || nilRec.Code != http.StatusOK {
		return fmt.Errorf("handler with nil propagator option failed to execute properly")
	}

	return nil
}

Seeder de origem

anônimo