CodeSampleX

Exemple

golang.org/x/net v0.12.0: html.NewTokenizer, html.EscapeString, html.UnescapeString

Échantillon vérifié pour golang golang.org/x/net v0.12.0: html.NewTokenizer, html.EscapeString, html.UnescapeString. Le contrat s'est exécuté sur go 1.26 …

sha256:e3d64a48e11afddd6be822c730a56d1f34c033c6c24d8b8edf84ee9997e6a108

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

Cas

HOW
Objectif
verify pkg:golang/golang.org/x/net@v0.12.0
Paquets
Symboles
  • golang.org/x/net/html.NewTokenizer
  • golang.org/x/net/html.EscapeString
  • golang.org/x/net/html.UnescapeString
Créé
2026-08-27T15:36:02Z

Contrat

  1. html.NewTokenizer tokenizes HTML stream and identifies start tags, end tags, self-closing tags, and text tokens with their attributes
  2. html.EscapeString and html.UnescapeString correctly escape and unescape special HTML characters like quotes, ampersands, and angle brackets

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code 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 pkg:golang/golang.org/x/net@v0.12.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/net@v0.12.0
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:647542d2abbec0c903b66c012b883004f23d4895623336cb7c9e6493bd3e5e91","contract":["html.NewTokenizer tokenizes HTML stream and identifies start tags, end tags, self-closing tags, and text tokens with their attributes","html.EscapeString and html.UnescapeString correctly escape and unescape special HTML characters like quotes, ampersands, and angle brackets"],"goal":"verify pkg:golang/golang.org/x/net@v0.12.0","kind":"HOW","packages":["pkg:golang/golang.org/x/net@v0.12.0"],"schemaVersion":1,"symbols":["golang.org/x/net/html.NewTokenizer","golang.org/x/net/html.EscapeString","golang.org/x/net/html.UnescapeString"]},"contractCommand":["go","run","./test"],"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/golang.org/x/net@v0.12.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/net@v0.12.0","symbols":["golang.org/x/net/html.NewTokenizer","golang.org/x/net/html.EscapeString","golang.org/x/net/html.UnescapeString"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22

require golang.org/x/net v0.12.0
go.sum
golang.org/x/net v0.12.0 h1:cfawfvKITfUsFCeJIHJrbSxpeu/E81khclypR0GVT50=
golang.org/x/net v0.12.0/go.mod h1:zEVYFnQC7m/vmpQFELhcD1EWkZlX69l4oqgmer6hfKA=
main.go
package main

import (
	"fmt"
	"io"
	"log"
	"strings"

	"golang.org/x/net/html"
)

func main() {
	rawHTML := `<div class="container"><a href="https://example.com">Link</a><img src="test.png" alt="Test" /></div>`

	fmt.Println("--- Tokenizer Demo ---")
	z := html.NewTokenizer(strings.NewReader(rawHTML))
	for {
		tt := z.Next()
		if tt == html.ErrorToken {
			err := z.Err()
			if err == io.EOF {
				break
			}
			log.Fatalf("tokenizer error: %v", err)
		}

		tok := z.Token()
		switch tt {
		case html.StartTagToken:
			fmt.Printf("Start tag: <%s>, attrs: %v\n", tok.Data, tok.Attr)
		case html.TextToken:
			fmt.Printf("Text: %q\n", tok.Data)
		case html.EndTagToken:
			fmt.Printf("End tag: </%s>\n", tok.Data)
		case html.SelfClosingTagToken:
			fmt.Printf("Self-closing tag: <%s/>, attrs: %v\n", tok.Data, tok.Attr)
		}
	}

	fmt.Println("\n--- Escape / Unescape Demo ---")
	original := `Hello <World> & "Friends"`
	escaped := html.EscapeString(original)
	unescaped := html.UnescapeString(escaped)

	fmt.Printf("Original:  %s\n", original)
	fmt.Printf("Escaped:   %s\n", escaped)
	fmt.Printf("Unescaped: %s\n", unescaped)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/golang.org/x/net@v0.12.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/net@v0.12.0"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.go
package main

import (
	"fmt"
	"io"
	"os"
	"strings"

	"golang.org/x/net/html"
)

func main() {
	// Assertion 1: html.NewTokenizer tokenizes HTML stream and identifies start tags, end tags, self-closing tags, and text tokens with their attributes
	{
		input := `<div id="main"><p class="text">Hello, World!</p><img src="example.png" alt="Image" /><!-- comment --></div>`
		z := html.NewTokenizer(strings.NewReader(input))

		type tokenRecord struct {
			tokType html.TokenType
			tag     string
			data    string
			attrs   map[string]string
		}

		var tokens []tokenRecord
		for {
			tt := z.Next()
			if tt == html.ErrorToken {
				if z.Err() == io.EOF {
					break
				}
				fmt.Fprintf(os.Stderr, "assertion 1 failed: tokenizer error: %v\n", z.Err())
				os.Exit(1)
			}

			tok := z.Token()
			attrs := make(map[string]string)
			for _, a := range tok.Attr {
				attrs[a.Key] = a.Val
			}

			tokens = append(tokens, tokenRecord{
				tokType: tt,
				tag:     tok.Data,
				data:    tok.Data,
				attrs:   attrs,
			})
		}

		if len(tokens) == 0 {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: expected tokens, got none\n")
			os.Exit(1)
		}

		// Verify StartTagToken <div id="main">
		if tokens[0].tokType != html.StartTagToken || tokens[0].tag != "div" || tokens[0].attrs["id"] != "main" {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: unexpected first token %+v\n", tokens[0])
			os.Exit(1)
		}

		// Verify StartTagToken <p class="text">
		if tokens[1].tokType != html.StartTagToken || tokens[1].tag != "p" || tokens[1].attrs["class"] != "text" {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: unexpected second token %+v\n", tokens[1])
			os.Exit(1)
		}

		// Verify TextToken "Hello, World!"
		if tokens[2].tokType != html.TextToken || tokens[2].data != "Hello, World!" {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: unexpected text token %+v\n", tokens[2])
			os.Exit(1)
		}

		// Verify EndTagToken </p>
		if tokens[3].tokType != html.EndTagToken || tokens[3].tag != "p" {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: unexpected end tag token %+v\n", tokens[3])
			os.Exit(1)
		}

		// Verify SelfClosingTagToken <img ... />
		if tokens[4].tokType != html.SelfClosingTagToken || tokens[4].tag != "img" || tokens[4].attrs["src"] != "example.png" || tokens[4].attrs["alt"] != "Image" {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: unexpected self-closing tag token %+v\n", tokens[4])
			os.Exit(1)
		}

		// Verify CommentToken
		if tokens[5].tokType != html.CommentToken || tokens[5].data != " comment " {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: unexpected comment token %+v\n", tokens[5])
			os.Exit(1)
		}

		// Verify EndTagToken </div>
		if tokens[6].tokType != html.EndTagToken || tokens[6].tag != "div" {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: unexpected final end tag token %+v\n", tokens[6])
			os.Exit(1)
		}

		// Also verify low-level TagName and TagAttr methods on tokenizer
		z2 := html.NewTokenizer(strings.NewReader(`<input type="text" name="user" required />`))
		if tt := z2.Next(); tt != html.SelfClosingTagToken {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: expected SelfClosingTagToken, got %v\n", tt)
			os.Exit(1)
		}
		tagName, hasAttr := z2.TagName()
		if string(tagName) != "input" || !hasAttr {
			fmt.Fprintf(os.Stderr, "assertion 1 failed: TagName expected 'input', true; got %q, %v\n", string(tagName), hasAttr)
			os.Exit(1)
		}
	}

	// Assertion 2: html.EscapeString and html.UnescapeString correctly escape and unescape special HTML characters like quotes, ampersands, and angle brackets
	{
		raw := `<b>"Fish & Chips" <'special'></b>`
		escaped := html.EscapeString(raw)
		expectedEscaped := `&lt;b&gt;&#34;Fish &amp; Chips&#34; &lt;&#39;special&#39;&gt;&lt;/b&gt;`
		if escaped != expectedEscaped {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected escaped %q, got %q\n", expectedEscaped, escaped)
			os.Exit(1)
		}

		unescaped := html.UnescapeString(escaped)
		if unescaped != raw {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected unescaped %q, got %q\n", raw, unescaped)
			os.Exit(1)
		}

		// Entity unescaping test
		entities := `&amp; &lt; &gt; &quot; &#39; &copy;`
		unescapedEntities := html.UnescapeString(entities)
		expectedEntities := `& < > " ' ©`
		if unescapedEntities != expectedEntities {
			fmt.Fprintf(os.Stderr, "assertion 2 failed: expected %q, got %q\n", expectedEntities, unescapedEntities)
			os.Exit(1)
		}
	}

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

Seeder d'origine

anonyme