CodeSampleX

Пример

github.com/json-iterator/go v1.1.11: jsoniter.Config

Проверенный пример — golang github.com/json-iterator/go v1.1.11: jsoniter.Config. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:a468780720aaf7a181095fa70888493de198db57550cfb7f4840b3b45661f940

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

Кейс

HOW
Цель
verify jsoniter.Config in pkg:golang/github.com/json-iterator/go@v1.1.11
Пакеты
Символы
  • jsoniter.Config
Окружение
go 1.26.6
Создан
2026-09-05T01:15:39Z

Контракт

  1. Config with SortMapKeys sorts map keys during serialization
  2. Config with EscapeHTML escapes HTML characters when true and preserves them when false
  3. Config with DisallowUnknownFields returns an error on unknown struct fields during unmarshal
  4. Config with UseNumber decodes JSON numbers as json.Number into interface{} values
  5. Config with TagKey reads struct field mappings from the custom tag key

Файлы

  • 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 jsoniter.Config in pkg:golang/github.com/json-iterator/go@v1.1.11
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/json-iterator/go@v1.1.11
Demonstrate these symbols/APIs:
  - jsoniter.Config

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:76bfafee6ce7be70c48a4044169ee30d05b2327f8c5ffae0c2d0b69605dd054a","contract":["Config with SortMapKeys sorts map keys during serialization","Config with EscapeHTML escapes HTML characters when true and preserves them when false","Config with DisallowUnknownFields returns an error on unknown struct fields during unmarshal","Config with UseNumber decodes JSON numbers as json.Number into interface{} values","Config with TagKey reads struct field mappings from the custom tag key"],"goal":"verify jsoniter.Config in pkg:golang/github.com/json-iterator/go@v1.1.11","kind":"HOW","packages":["pkg:golang/github.com/json-iterator/go@v1.1.11"],"schemaVersion":1,"symbols":["jsoniter.Config"]},"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/github.com/json-iterator/go@v1.1.11"],"schemaVersion":1,"subject":"pkg:golang/github.com/json-iterator/go@v1.1.11","symbols":["jsoniter.Config"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22

require github.com/json-iterator/go v1.1.11

require (
	github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
	github.com/modern-go/reflect2 v1.0.2 // indirect
)
go.sum
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
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/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/json-iterator/go v1.1.11 h1:uVUAXhF2To8cbw/3xN3pxj6kk7TYKs98NIrTqPlMWAQ=
github.com/json-iterator/go v1.1.11/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLDQ0W1YjYsBW+p8U2u7vzgW2SQVmlNazg=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
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/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
main.go
package main

import (
	"fmt"
	"log"

	jsoniter "github.com/json-iterator/go"
)

type UserPayload struct {
	Name string `json:"name"`
	Role string `json:"role"`
}

func main() {
	// Configure customized jsoniter instance
	customConfig := jsoniter.Config{
		EscapeHTML:             true,
		SortMapKeys:            true,
		ValidateJsonRawMessage: true,
		DisallowUnknownFields:  true,
	}
	jsonAPI := customConfig.Froze()

	// 1. Marshal map with sorted keys
	dataMap := map[string]string{
		"z_key": "last",
		"a_key": "first",
		"m_key": "middle",
	}
	encoded, err := jsonAPI.MarshalToString(dataMap)
	if err != nil {
		log.Fatalf("failed to marshal map: %v", err)
	}
	fmt.Printf("Serialized sorted map: %s\n", encoded)

	// 2. Unmarshal with unknown field checking
	jsonInput := `{"name":"sample_user","role":"admin"}`
	var payload UserPayload
	if err := jsonAPI.UnmarshalFromString(jsonInput, &payload); err != nil {
		log.Fatalf("failed to unmarshal: %v", err)
	}
	fmt.Printf("Parsed payload: name=%s, role=%s\n", payload.Name, payload.Role)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify jsoniter.Config in pkg:golang/github.com/json-iterator/go@v1.1.11",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/json-iterator/go@v1.1.11"
  ],
  "symbols": [
    "jsoniter.Config"
  ]
}
test/contract.go
package main

import (
	"encoding/json"
	"fmt"
	"os"

	jsoniter "github.com/json-iterator/go"
)

type strictPayload struct {
	KnownField string `json:"known_field"`
}

type taggedPayload struct {
	CustomField string `custom:"target_key"`
}

func main() {
	// Assertion 1: Config with SortMapKeys sorts map keys during serialization
	sortConfig := jsoniter.Config{SortMapKeys: true}.Froze()
	testMap := map[string]int{
		"z_key": 3,
		"a_key": 1,
		"m_key": 2,
	}
	sortedJSON, err := sortConfig.MarshalToString(testMap)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: sortConfig.MarshalToString error: %v\n", err)
		os.Exit(1)
	}
	expectedMapJSON := `{"a_key":1,"m_key":2,"z_key":3}`
	if sortedJSON != expectedMapJSON {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: got %q, expected %q\n", sortedJSON, expectedMapJSON)
		os.Exit(1)
	}

	// Assertion 2: Config with EscapeHTML escapes HTML characters when true and preserves them when false
	escapeConfig := jsoniter.Config{EscapeHTML: true}.Froze()
	rawConfig := jsoniter.Config{EscapeHTML: false}.Froze()
	htmlInput := "<test>&value</test>"

	escapedJSON, err := escapeConfig.MarshalToString(htmlInput)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: escapeConfig.MarshalToString error: %v\n", err)
		os.Exit(1)
	}
	expectedEscaped := `"\u003ctest\u003e\u0026value\u003c/test\u003e"`
	if escapedJSON != expectedEscaped {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: got %q, expected %q\n", escapedJSON, expectedEscaped)
		os.Exit(1)
	}

	rawJSON, err := rawConfig.MarshalToString(htmlInput)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: rawConfig.MarshalToString error: %v\n", err)
		os.Exit(1)
	}
	expectedRaw := `"<test>&value</test>"`
	if rawJSON != expectedRaw {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: got %q, expected %q\n", rawJSON, expectedRaw)
		os.Exit(1)
	}

	// Assertion 3: Config with DisallowUnknownFields returns an error on unknown struct fields during unmarshal
	strictConfig := jsoniter.Config{DisallowUnknownFields: true}.Froze()
	var payload strictPayload
	validJSON := `{"known_field":"valid_data"}`
	if err := strictConfig.UnmarshalFromString(validJSON, &payload); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: valid input returned error: %v\n", err)
		os.Exit(1)
	}
	if payload.KnownField != "valid_data" {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: payload mismatch: got %q\n", payload.KnownField)
		os.Exit(1)
	}

	invalidJSON := `{"known_field":"valid_data","unknown_field":"unexpected"}`
	if err := strictConfig.UnmarshalFromString(invalidJSON, &payload); err == nil {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: expected error for unknown field, got nil\n")
		os.Exit(1)
	}

	// Assertion 4: Config with UseNumber decodes JSON numbers as json.Number into interface{} values
	numConfig := jsoniter.Config{UseNumber: true}.Froze()
	var decodedNum interface{}
	numJSON := `9007199254740993`
	if err := numConfig.UnmarshalFromString(numJSON, &decodedNum); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: numConfig.UnmarshalFromString error: %v\n", err)
		os.Exit(1)
	}
	jsonNum, ok := decodedNum.(json.Number)
	if !ok {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: decoded value is not json.Number (got %T)\n", decodedNum)
		os.Exit(1)
	}
	if jsonNum.String() != numJSON {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: jsonNum mismatch: got %q, expected %q\n", jsonNum.String(), numJSON)
		os.Exit(1)
	}

	// Assertion 5: Config with TagKey reads struct field mappings from the custom tag key
	customTagConfig := jsoniter.Config{TagKey: "custom"}.Froze()
	var tagged taggedPayload
	taggedJSON := `{"target_key":"custom_tag_value"}`
	if err := customTagConfig.UnmarshalFromString(taggedJSON, &tagged); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: customTagConfig.UnmarshalFromString error: %v\n", err)
		os.Exit(1)
	}
	if tagged.CustomField != "custom_tag_value" {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: tagged field mismatch: got %q, expected %q\n", tagged.CustomField, "custom_tag_value")
		os.Exit(1)
	}

	marshaledCustom, err := customTagConfig.MarshalToString(tagged)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: customTagConfig.MarshalToString error: %v\n", err)
		os.Exit(1)
	}
	if marshaledCustom != taggedJSON {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: marshaledCustom mismatch: got %q, expected %q\n", marshaledCustom, taggedJSON)
		os.Exit(1)
	}

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

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

аноним