CodeSampleX

Пример

google.golang.org/protobuf v1.36.11: protojson.Unmarshal

Проверенный пример — golang google.golang.org/protobuf v1.36.11: protojson.Unmarshal. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден…

sha256:f01f4e7950b157f2ca93a59b6ddf3f9d78a051506613d4aefc1a4e98b42c5f1a

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

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

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

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 go

Среды запусков проверки

Окружение Контракт Этапы Запуск
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-02

Кейс

HOW
Цель
verify protojson.Unmarshal in pkg:golang/google.golang.org/protobuf@v1.36.11
Пакеты
Символы
  • protojson.Unmarshal
Создан
2026-09-02T08:49:09Z

Контракт

  1. protojson.Unmarshal unmarshals RFC 3339 timestamp JSON string into timestamppb.Timestamp
  2. protojson.Unmarshal unmarshals JSON object into structpb.Struct preserving string, number, and boolean fields
  3. protojson.Unmarshal returns error when given invalid JSON input

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.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 protojson.Unmarshal in pkg:golang/google.golang.org/protobuf@v1.36.11
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.36.11
Demonstrate these symbols/APIs:
  - protojson.Unmarshal

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:16a2ca220196f1a6107cecfec8588ee1e7c04ef28d48774b79bfc37d7f22daae","contract":["protojson.Unmarshal unmarshals RFC 3339 timestamp JSON string into timestamppb.Timestamp","protojson.Unmarshal unmarshals JSON object into structpb.Struct preserving string, number, and boolean fields","protojson.Unmarshal returns error when given invalid JSON input"],"goal":"verify protojson.Unmarshal in pkg:golang/google.golang.org/protobuf@v1.36.11","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.36.11"],"schemaVersion":1,"symbols":["protojson.Unmarshal"]},"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/google.golang.org/protobuf@v1.36.11"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.36.11","symbols":["protojson.Unmarshal"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.23

require google.golang.org/protobuf v1.36.11
go.sum
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
sample.go
package sample

import (
	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

// UnmarshalTimestamp parses JSON into a google.protobuf.Timestamp message.
func UnmarshalTimestamp(data []byte) (*timestamppb.Timestamp, error) {
	var ts timestamppb.Timestamp
	if err := protojson.Unmarshal(data, &ts); err != nil {
		return nil, err
	}
	return &ts, nil
}

// UnmarshalStruct parses JSON into a google.protobuf.Struct message.
func UnmarshalStruct(data []byte) (*structpb.Struct, error) {
	var s structpb.Struct
	if err := protojson.Unmarshal(data, &s); err != nil {
		return nil, err
	}
	return &s, nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify protojson.Unmarshal in pkg:golang/google.golang.org/protobuf@v1.36.11",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.36.11"
  ],
  "symbols": [
    "protojson.Unmarshal"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"

	"sample"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func main() {
	// 1. Unmarshal valid JSON timestamp into timestamppb.Timestamp
	tsJSON := []byte(`"1970-01-01T00:00:10Z"`)
	var ts timestamppb.Timestamp
	if err := protojson.Unmarshal(tsJSON, &ts); err != nil {
		fmt.Fprintf(os.Stderr, "contract failed: unmarshal timestamp error: %v\n", err)
		os.Exit(1)
	}
	if ts.Seconds != 10 {
		fmt.Fprintf(os.Stderr, "contract failed: expected seconds 10, got %d\n", ts.Seconds)
		os.Exit(1)
	}

	// 2. Unmarshal valid JSON object into structpb.Struct
	structJSON := []byte(`{"name":"example","count":100,"enabled":true}`)
	var s structpb.Struct
	if err := protojson.Unmarshal(structJSON, &s); err != nil {
		fmt.Fprintf(os.Stderr, "contract failed: unmarshal struct error: %v\n", err)
		os.Exit(1)
	}
	fields := s.GetFields()
	if fields["name"].GetStringValue() != "example" {
		fmt.Fprintf(os.Stderr, "contract failed: field 'name' mismatch\n")
		os.Exit(1)
	}
	if fields["count"].GetNumberValue() != 100 {
		fmt.Fprintf(os.Stderr, "contract failed: field 'count' mismatch\n")
		os.Exit(1)
	}
	if !fields["enabled"].GetBoolValue() {
		fmt.Fprintf(os.Stderr, "contract failed: field 'enabled' mismatch\n")
		os.Exit(1)
	}

	// 3. Unmarshal invalid JSON returns error
	invalidJSON := []byte(`{invalid: json}`)
	var invalidMsg structpb.Struct
	if err := protojson.Unmarshal(invalidJSON, &invalidMsg); err == nil {
		fmt.Fprintf(os.Stderr, "contract failed: expected error for invalid JSON, got nil\n")
		os.Exit(1)
	}

	// 4. Verify helper functions work
	tsHelper, err := sample.UnmarshalTimestamp(tsJSON)
	if err != nil || tsHelper.Seconds != 10 {
		fmt.Fprintf(os.Stderr, "contract failed: sample.UnmarshalTimestamp error: %v\n", err)
		os.Exit(1)
	}

	sHelper, err := sample.UnmarshalStruct(structJSON)
	if err != nil || sHelper.GetFields()["name"].GetStringValue() != "example" {
		fmt.Fprintf(os.Stderr, "contract failed: sample.UnmarshalStruct error: %v\n", err)
		os.Exit(1)
	}

	fmt.Println("PASS")
}

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

аноним