CodeSampleX

샘플

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

검증된 샘플 — golang go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0: Labeler. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:df1fa7f06d79418a314c02e7fe2f02afbd00d0ca3ec32c70e1d8eb88a32c42e7

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
verify otelhttp.Labeler in pkg:golang/go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp@v0.68.0
패키지
심벌
  • otelhttp.Labeler
환경
go 1.26.6
생성일
2026-09-07T04:58:33Z

컨트랙트

  1. otelhttp.LabelerFromContext returns non-nil Labeler and false when context has no Labeler
  2. Labeler.Add appends attribute key-values accessible via Labeler.Get
  3. otelhttp.ContextWithLabeler attaches Labeler to context and LabelerFromContext retrieves it
  4. otelhttp.NewHandler injects Labeler into request context during HTTP request handling

파일

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • labeler.go
  • spec.json
  • test/contract_test.go

소스 아티팩트 내려받기 (tar.gz)

소스

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.Labeler 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.Labeler

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:217028c9d409163f72d6706b91241e05a1ece20360b29643d5694dac89d20115","contract":["otelhttp.LabelerFromContext returns non-nil Labeler and false when context has no Labeler","Labeler.Add appends attribute key-values accessible via Labeler.Get","otelhttp.ContextWithLabeler attaches Labeler to context and LabelerFromContext retrieves it","otelhttp.NewHandler injects Labeler into request context during HTTP request handling"],"goal":"verify otelhttp.Labeler 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.Labeler"]},"contractCommand":["go","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.Labeler"],"verifierAdapter":"golang@1"}
go.mod
module example.com/otelhttp-labeler

go 1.26.6

require (
	go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0
	go.opentelemetry.io/otel 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.opentelemetry.io/otel/trace 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=
labeler.go
package sample

import (
	"context"
	"net/http"

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

// AddRouteLabel extracts the Labeler from the request context and adds an http.route attribute.
// Returns true if a Labeler was explicitly found in the context.
func AddRouteLabel(r *http.Request, route string) bool {
	labeler, ok := otelhttp.LabelerFromContext(r.Context())
	if !ok {
		return false
	}
	labeler.Add(attribute.String("http.route", route))
	return true
}

// NewDecoratedHandler wraps an http.Handler with otelhttp.NewHandler to provide automatic
// Labeler injection and OpenTelemetry HTTP instrumentation.
func NewDecoratedHandler(handler http.Handler, operation string, opts ...otelhttp.Option) http.Handler {
	return otelhttp.NewHandler(handler, operation, opts...)
}

// InjectLabeler returns a new context with the given Labeler attached.
func InjectLabeler(ctx context.Context, labeler *otelhttp.Labeler) context.Context {
	return otelhttp.ContextWithLabeler(ctx, labeler)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify otelhttp.Labeler 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.Labeler"
  ]
}
test/contract_test.go
package sample_test

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

	sample "example.com/otelhttp-labeler"
	"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
	"go.opentelemetry.io/otel/attribute"
)

func TestLabelerContract(t *testing.T) {
	// 1. otelhttp.LabelerFromContext returns non-nil Labeler and false when context has no Labeler
	t.Run("EmptyContext", func(t *testing.T) {
		emptyCtx := context.Background()
		labeler, ok := otelhttp.LabelerFromContext(emptyCtx)
		if labeler == nil {
			t.Fatal("expected non-nil labeler from empty context")
		}
		if ok {
			t.Fatal("expected ok=false for empty context")
		}
	})

	// 2. Labeler.Add appends attribute key-values accessible via Labeler.Get
	t.Run("AddAndGetAttributes", func(t *testing.T) {
		labeler := &otelhttp.Labeler{}
		labeler.Add(attribute.String("test.key", "test.value"), attribute.Int("test.count", 42))
		attrs := labeler.Get()
		if len(attrs) != 2 {
			t.Fatalf("expected 2 attributes, got %d", len(attrs))
		}
		if attrs[0].Key != "test.key" || attrs[0].Value.AsString() != "test.value" {
			t.Fatalf("unexpected attribute 0: %+v", attrs[0])
		}
		if attrs[1].Key != "test.count" || attrs[1].Value.AsInt64() != 42 {
			t.Fatalf("unexpected attribute 1: %+v", attrs[1])
		}
	})

	// 3. otelhttp.ContextWithLabeler attaches Labeler to context and LabelerFromContext retrieves it
	t.Run("ContextWithLabeler", func(t *testing.T) {
		labeler := &otelhttp.Labeler{}
		ctx := sample.InjectLabeler(context.Background(), labeler)
		retrieved, ok := otelhttp.LabelerFromContext(ctx)
		if !ok {
			t.Fatal("expected ok=true when Labeler is attached")
		}
		if retrieved != labeler {
			t.Fatal("retrieved labeler pointer does not match attached labeler")
		}
	})

	// 4. otelhttp.NewHandler injects Labeler into request context during HTTP request handling
	t.Run("NewHandlerInjectsLabeler", func(t *testing.T) {
		var receivedLabeler bool
		var attrCount int

		inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			receivedLabeler = sample.AddRouteLabel(r, "/api/v1/resource")
			labeler, _ := otelhttp.LabelerFromContext(r.Context())
			attrCount = len(labeler.Get())
			w.WriteHeader(http.StatusOK)
		})

		handler := sample.NewDecoratedHandler(inner, "test-op")
		req := httptest.NewRequest(http.MethodGet, "http://localhost/api/v1/resource", nil)
		rec := httptest.NewRecorder()

		handler.ServeHTTP(rec, req)

		if !receivedLabeler {
			t.Fatal("expected AddRouteLabel to return true inside otelhttp handler")
		}
		if attrCount != 1 {
			t.Fatalf("expected 1 attribute attached, got %d", attrCount)
		}
		if rec.Code != http.StatusOK {
			t.Fatalf("expected status 200, got %d", rec.Code)
		}
	})
}

오리진 시더

익명