CodeSampleX

Sample

go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0: NewHandler

Verified sample for golang go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0: NewHandler. The contract ran on go 1.26 · linux debian/x64…

sha256:61a24e26073bdb33dfcc2a3893a84e88250f1bef8760a28f6254c80ad71d8118

This network offers one thing: a sample that builds. It ran the sample in a sandbox and kept the signed receipt. It grades nothing and warrants nothing — whether the same code builds where you are is not something it measured. How many distinct signing keys filed a passing contract receipt. One is the author alone; more than one means somebody else built it too. A key is self-generated with nothing registered behind it, so it counts keys, not people. MIT-0

Execution evidence

The declared environment and the signed runs are kept apart, so you can see exactly what this sample ran and where.

Evidence basis
Signed contract pass
Verification receipts
1
Signing keys that built it
1
Declared environment linux 24 · ubuntu · glibc 2.39 x64 go

Verification-run environments

Environment Contract Stages Run
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-10

Case

HOW
Goal
verify go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.NewHandler in pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.70.0
Packages
Symbols
  • go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.NewHandler
Created
2026-09-10T22:28:07Z

Contract

  1. NewHandler wraps an http.Handler with OpenTelemetry server span instrumentation.
  2. NewHandler injects a valid SpanContext into the request context accessible by inner handlers.
  3. NewHandler formats span name dynamically using WithSpanNameFormatter.
  4. NewHandler skips tracing for requests excluded by WithFilter.
  5. NewHandler records response status code on the completed server span.

Files

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • handler.go
  • handler_test.go
  • spec.json

Download the source artifact (tar.gz)

Source

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 go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.NewHandler in pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.70.0
Kind: HOW

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

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:3f4d876f09ab6b922febf20fd34473fe488a70582954f6363bd561fb71aa3404","contract":["NewHandler wraps an http.Handler with OpenTelemetry server span instrumentation.","NewHandler injects a valid SpanContext into the request context accessible by inner handlers.","NewHandler formats span name dynamically using WithSpanNameFormatter.","NewHandler skips tracing for requests excluded by WithFilter.","NewHandler records response status code on the completed server span."],"goal":"verify go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.NewHandler in pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.70.0","kind":"HOW","packages":["pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.70.0"],"schemaVersion":1,"symbols":["go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.NewHandler"]},"contractCommand":["go","test","-v","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.70.0"],"schemaVersion":1,"subject":"pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.70.0","symbols":["go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.NewHandler"],"verifierAdapter":"golang@1"}
go.mod
module example.com/otelhttp-sample

go 1.26.6

require (
	go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0
	go.opentelemetry.io/otel/sdk v1.45.0
	go.opentelemetry.io/otel/trace v1.45.0
)

require (
	github.com/cespare/xxhash/v2 v2.3.0 // indirect
	github.com/felixge/httpsnoop v1.1.0 // indirect
	github.com/go-logr/logr v1.4.4 // indirect
	github.com/go-logr/stdr v1.2.2 // indirect
	github.com/google/uuid v1.6.0 // indirect
	go.opentelemetry.io/auto/sdk v1.2.1 // indirect
	go.opentelemetry.io/otel v1.45.0 // indirect
	go.opentelemetry.io/otel/metric v1.45.0 // indirect
	golang.org/x/sys v0.47.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.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
github.com/go-logr/logr v1.4.4/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.70.0 h1:LMuyCAyfalSjDyjdC65nK6N0zoTT63+E/u95X0JovZI=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0/go.mod h1:085m8qbm4hgc8rZWGDEa4vmyyo2c3nPxUslYUKUIU04=
go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA=
go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA=
go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.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=
handler.go
package sample

import (
	"fmt"
	"net/http"

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

// ServerOptions holds configurable options for creating instrumented handlers.
type ServerOptions struct {
	TracerProvider trace.TracerProvider
	Filter         otelhttp.Filter
	NameFormatter  func(operation string, r *http.Request) string
}

// WrapHandler wraps the given http.Handler with OpenTelemetry instrumentation
// using otelhttp.NewHandler with the specified operation name and options.
func WrapHandler(base http.Handler, operation string, opts ServerOptions) http.Handler {
	var otelOpts []otelhttp.Option
	if opts.TracerProvider != nil {
		otelOpts = append(otelOpts, otelhttp.WithTracerProvider(opts.TracerProvider))
	}
	if opts.Filter != nil {
		otelOpts = append(otelOpts, otelhttp.WithFilter(opts.Filter))
	}
	if opts.NameFormatter != nil {
		otelOpts = append(otelOpts, otelhttp.WithSpanNameFormatter(opts.NameFormatter))
	}
	return otelhttp.NewHandler(base, operation, otelOpts...)
}

// HelloHandler returns a simple HTTP handler that reads the active span from context
// and writes a response header and body.
func HelloHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		span := trace.SpanFromContext(r.Context())
		if span.SpanContext().IsValid() {
			w.Header().Set("X-Trace-ID", span.SpanContext().TraceID().String())
		}
		w.WriteHeader(http.StatusOK)
		_, _ = fmt.Fprint(w, "hello from instrumented handler")
	})
}
handler_test.go
package sample_test

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"

	sample "example.com/otelhttp-sample"
	sdktrace "go.opentelemetry.io/otel/sdk/trace"
	"go.opentelemetry.io/otel/sdk/trace/tracetest"
	"go.opentelemetry.io/otel/trace"
)

func TestNewHandlerContract(t *testing.T) {
	ctx := context.Background()
	exporter := tracetest.NewInMemoryExporter()
	tp := sdktrace.NewTracerProvider(
		sdktrace.WithSyncer(exporter),
	)
	defer func() { _ = tp.Shutdown(ctx) }()

	// 1. NewHandler wraps an http.Handler with OpenTelemetry server span instrumentation.
	var capturedSpanCtx trace.SpanContext
	innerHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		span := trace.SpanFromContext(r.Context())
		capturedSpanCtx = span.SpanContext()
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("response-body"))
	})

	instrumented := sample.WrapHandler(innerHandler, "users-endpoint", sample.ServerOptions{
		TracerProvider: tp,
	})

	req1 := httptest.NewRequest(http.MethodGet, "http://localhost:8080/users", nil)
	rec1 := httptest.NewRecorder()
	instrumented.ServeHTTP(rec1, req1)

	if rec1.Code != http.StatusOK {
		t.Fatalf("expected status 200, got %d", rec1.Code)
	}
	spans := exporter.GetSpans()
	if len(spans) != 1 {
		t.Fatalf("expected 1 span, got %d", len(spans))
	}
	if spans[0].SpanKind != trace.SpanKindServer {
		t.Fatalf("expected server span kind, got %v", spans[0].SpanKind)
	}
	if spans[0].Name != "GET" {
		t.Fatalf("expected default span name 'GET', got %q", spans[0].Name)
	}

	// 2. NewHandler injects a valid SpanContext into the request context accessible by inner handlers.
	if !capturedSpanCtx.IsValid() {
		t.Fatal("captured span context in inner handler is invalid")
	}
	if capturedSpanCtx.TraceID() != spans[0].SpanContext.TraceID() {
		t.Fatalf("trace ID mismatch: inner context %s, recorded span %s",
			capturedSpanCtx.TraceID(), spans[0].SpanContext.TraceID())
	}

	// 3. NewHandler formats span name dynamically using WithSpanNameFormatter.
	exporter.Reset()
	customFormatter := func(operation string, r *http.Request) string {
		return r.Method + " " + r.URL.Path
	}
	formattedHandler := sample.WrapHandler(innerHandler, "fallback-name", sample.ServerOptions{
		TracerProvider: tp,
		NameFormatter:  customFormatter,
	})

	req2 := httptest.NewRequest(http.MethodPost, "http://localhost:8080/items/create", strings.NewReader("data"))
	rec2 := httptest.NewRecorder()
	formattedHandler.ServeHTTP(rec2, req2)

	spans = exporter.GetSpans()
	if len(spans) != 1 {
		t.Fatalf("expected 1 span for formatted handler, got %d", len(spans))
	}
	if spans[0].Name != "POST /items/create" {
		t.Fatalf("expected span name 'POST /items/create', got %q", spans[0].Name)
	}

	// 4. NewHandler skips tracing for requests excluded by WithFilter.
	exporter.Reset()
	filter := func(r *http.Request) bool {
		return r.URL.Path != "/healthz"
	}
	filteredHandler := sample.WrapHandler(innerHandler, "filtered-op", sample.ServerOptions{
		TracerProvider: tp,
		Filter:         filter,
	})

	reqHealth := httptest.NewRequest(http.MethodGet, "http://localhost:8080/healthz", nil)
	recHealth := httptest.NewRecorder()
	filteredHandler.ServeHTTP(recHealth, reqHealth)

	if len(exporter.GetSpans()) != 0 {
		t.Fatalf("expected 0 spans for filtered path /healthz, got %d", len(exporter.GetSpans()))
	}

	reqActive := httptest.NewRequest(http.MethodGet, "http://localhost:8080/active", nil)
	recActive := httptest.NewRecorder()
	filteredHandler.ServeHTTP(recActive, reqActive)

	if len(exporter.GetSpans()) != 1 {
		t.Fatalf("expected 1 span for active request, got %d", len(exporter.GetSpans()))
	}

	// 5. NewHandler records response status code on the completed server span.
	exporter.Reset()
	errorHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusNotFound)
		_, _ = w.Write([]byte("not found"))
	})
	errorInstrumented := sample.WrapHandler(errorHandler, "error-op", sample.ServerOptions{
		TracerProvider: tp,
	})

	req404 := httptest.NewRequest(http.MethodGet, "http://localhost:8080/missing", nil)
	rec404 := httptest.NewRecorder()
	errorInstrumented.ServeHTTP(rec404, req404)

	if rec404.Code != http.StatusNotFound {
		t.Fatalf("expected status 404, got %d", rec404.Code)
	}
	spans = exporter.GetSpans()
	if len(spans) != 1 {
		t.Fatalf("expected 1 span for 404 response, got %d", len(spans))
	}

	// 6. Verify HelloHandler helper
	helloHandler := sample.HelloHandler()
	helloInstrumented := sample.WrapHandler(helloHandler, "hello-op", sample.ServerOptions{
		TracerProvider: tp,
	})
	reqHello := httptest.NewRequest(http.MethodGet, "http://localhost:8080/hello", nil)
	recHello := httptest.NewRecorder()
	helloInstrumented.ServeHTTP(recHello, reqHello)

	body, _ := io.ReadAll(recHello.Body)
	if !strings.Contains(string(body), "hello from instrumented handler") {
		t.Fatalf("unexpected body: %s", string(body))
	}
	if recHello.Header().Get("X-Trace-ID") == "" {
		t.Fatal("expected X-Trace-ID header to be populated")
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.NewHandler in pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.70.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.70.0"
  ],
  "symbols": [
    "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp.NewHandler"
  ]
}

Origin Seeder

anonymous