CodeSampleX

Пример

github.com/julienschmidt/httprouter v1.3.0

Проверенный пример — golang github.com/julienschmidt/httprouter v1.3.0. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:51231b6cab008ac2c3c7e65a7d57f81da16c4269dd8a811e830365c3cbec51c4

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда go 1.26 linux 24 · ubuntu · glibc 2.39 amd64 go 1.26 go 1.26 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-14

Кейс

HOW
Цель
verify pkg:golang/github.com/julienschmidt/httprouter@v1.3.0
Пакеты
Окружение
go 1.26.6
Создан
2026-09-14T09:41:52Z

Контракт

  1. httprouter.New returns an initialized Router
  2. Router.GET routes GET requests with named path parameters
  3. Router.POST routes POST requests with body content
  4. Router.NotFound executes custom handler for unmatched routes
  5. Router.PanicHandler intercepts panics during request handling

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/contract.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 pkg:golang/github.com/julienschmidt/httprouter@v1.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/julienschmidt/httprouter@v1.3.0

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:5a67f1228e6ced519199b73714595422d6d9c03641dde358899239c13ea88f6f","contract":["httprouter.New returns an initialized Router","Router.GET routes GET requests with named path parameters","Router.POST routes POST requests with body content","Router.NotFound executes custom handler for unmatched routes","Router.PanicHandler intercepts panics during request handling"],"goal":"verify pkg:golang/github.com/julienschmidt/httprouter@v1.3.0","kind":"HOW","packages":["pkg:golang/github.com/julienschmidt/httprouter@v1.3.0"],"schemaVersion":1},"contractCommand":["go","run","./test"],"environment":{"arch":"amd64","compiler":"go","compilerVersion":"1.26.6","distro":"ubuntu","ecosystem":"golang","language":"go","languageVersion":"1.26.6","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/github.com/julienschmidt/httprouter@v1.3.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/julienschmidt/httprouter@v1.3.0","verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/julienschmidt/httprouter v1.3.0
go.sum
github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U=
github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM=
main.go
package main

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

	"github.com/julienschmidt/httprouter"
)

func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	fmt.Fprint(w, "Welcome!\n")
}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

func main() {
	router := httprouter.New()
	router.GET("/", Index)
	router.GET("/hello/:name", Hello)

	req, _ := http.NewRequest("GET", "/hello/gopher", nil)
	rr := httptest.NewRecorder()
	router.ServeHTTP(rr, req)

	fmt.Printf("Response: %s", rr.Body.String())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/julienschmidt/httprouter@v1.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/julienschmidt/httprouter@v1.3.0"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"

	"github.com/julienschmidt/httprouter"
)

func main() {
	// Assertion 1: httprouter.New returns an initialized Router
	{
		router := httprouter.New()
		if router == nil {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: router is nil\n")
			os.Exit(1)
		}
		var _ http.Handler = router
	}

	// Assertion 2: Router.GET routes GET requests with named path parameters
	{
		router := httprouter.New()
		var capturedParam string
		router.GET("/users/:id", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
			capturedParam = ps.ByName("id")
			w.WriteHeader(http.StatusOK)
			fmt.Fprint(w, "user-found")
		})

		req := httptest.NewRequest("GET", "/users/42", nil)
		rec := httptest.NewRecorder()
		router.ServeHTTP(rec, req)

		if rec.Code != http.StatusOK {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected status 200, got %d\n", rec.Code)
			os.Exit(1)
		}
		if capturedParam != "42" {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected param '42', got %q\n", capturedParam)
			os.Exit(1)
		}
		if rec.Body.String() != "user-found" {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected body 'user-found', got %q\n", rec.Body.String())
			os.Exit(1)
		}
	}

	// Assertion 3: Router.POST routes POST requests with body content
	{
		router := httprouter.New()
		var receivedBody string
		router.POST("/submit", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
			b, err := io.ReadAll(r.Body)
			if err != nil {
				w.WriteHeader(http.StatusInternalServerError)
				return
			}
			receivedBody = string(b)
			w.WriteHeader(http.StatusCreated)
		})

		payload := "item=alpha"
		req := httptest.NewRequest("POST", "/submit", strings.NewReader(payload))
		rec := httptest.NewRecorder()
		router.ServeHTTP(rec, req)

		if rec.Code != http.StatusCreated {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: expected status 201, got %d\n", rec.Code)
			os.Exit(1)
		}
		if receivedBody != payload {
			fmt.Fprintf(os.Stderr, "assertion 3 failed: expected body %q, got %q\n", payload, receivedBody)
			os.Exit(1)
		}
	}

	// Assertion 4: Router.NotFound executes custom handler for unmatched routes
	{
		router := httprouter.New()
		customNotFoundCalled := false
		router.NotFound = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			customNotFoundCalled = true
			w.WriteHeader(http.StatusNotFound)
			fmt.Fprint(w, "custom-404")
		})

		req := httptest.NewRequest("GET", "/nonexistent", nil)
		rec := httptest.NewRecorder()
		router.ServeHTTP(rec, req)

		if !customNotFoundCalled {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: custom NotFound handler not called\n")
			os.Exit(1)
		}
		if rec.Code != http.StatusNotFound {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: expected status 404, got %d\n", rec.Code)
			os.Exit(1)
		}
		if rec.Body.String() != "custom-404" {
			fmt.Fprintf(os.Stderr, "assertion 4 failed: expected body 'custom-404', got %q\n", rec.Body.String())
			os.Exit(1)
		}
	}

	// Assertion 5: Router.PanicHandler intercepts panics during request handling
	{
		router := httprouter.New()
		panicCaught := false
		router.PanicHandler = func(w http.ResponseWriter, r *http.Request, p interface{}) {
			panicCaught = true
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprint(w, "recovered")
		}
		router.GET("/panic", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
			panic("something went wrong")
		})

		req := httptest.NewRequest("GET", "/panic", nil)
		rec := httptest.NewRecorder()
		router.ServeHTTP(rec, req)

		if !panicCaught {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: panic was not caught\n")
			os.Exit(1)
		}
		if rec.Code != http.StatusInternalServerError {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: expected status 500, got %d\n", rec.Code)
			os.Exit(1)
		}
		if rec.Body.String() != "recovered" {
			fmt.Fprintf(os.Stderr, "assertion 5 failed: expected body 'recovered', got %q\n", rec.Body.String())
			os.Exit(1)
		}
	}

	fmt.Println("All contract assertions passed successfully.")
}

Исходный сидер

аноним