CodeSampleX

샘플

google.golang.org/protobuf v1.32.0: protojson

검증된 샘플 — golang google.golang.org/protobuf v1.32.0: protojson. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다: protojson.Marshal and…

sha256:ffce65174b807a06ad11075277b385403fc72b0e483c22cf5df33ff4e8f56f62

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

실행 증거

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

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 go linux 24 · ubuntu · glibc 2.39 x64 go go 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-01

케이스

HOW
목표
verify google.golang.org/protobuf/encoding/protojson in pkg:golang/google.golang.org/protobuf@v1.32.0
패키지
심벌
  • google.golang.org/protobuf/encoding/protojson
환경
go
생성일
2026-09-01T06:07:45Z

컨트랙트

  1. protojson.Marshal and protojson.Unmarshal roundtrip message fields with camelCase naming for fields, string representation for enums, and string representation for 64-bit integers.
  2. protojson.MarshalOptions.UseProtoNames outputs original protobuf snake_case field names instead of camelCase.
  3. protojson.MarshalOptions.EmitUnpopulated includes unpopulated fields with default zero values in the resulting JSON output.
  4. protojson.MarshalOptions.UseEnumNumbers outputs integer numbers for enum fields instead of string enum names.
  5. protojson.UnmarshalOptions.DiscardUnknown ignores unknown fields in JSON payload when true and returns an error when false.
  6. protojson formats Google well-known types (Timestamp as RFC 3339 string, Duration as second string suffix, and Struct/Value as JSON objects).

파일

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • protojson_test.go
  • spec.json

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

소스

NOTES.md
# Protocol Buffers JSON Serialization with protojson

This sample verifies JSON encoding and decoding semantics of `google.golang.org/protobuf/encoding/protojson` pinned to version `v1.32.0`.

## Verified Behaviors

1. **Marshal and Unmarshal Roundtrip**:
   - `protojson.Marshal` converts protocol buffer message fields to JSON using camelCase field names by default.
   - Enums are marshaled using their string name identifiers.
   - 64-bit integers (`int64`, `uint64`, `sint64`, etc.) are marshaled as strings per the proto3 JSON specification.
   - `protojson.Unmarshal` parses the JSON representation back into a protocol buffer message preserving field values.

2. **MarshalOptions**:
   - `UseProtoNames: true`: Formats JSON keys using original protobuf snake_case field names instead of camelCase.
   - `EmitUnpopulated: true`: Emits fields with default zero values (e.g. empty strings, false, 0) in the output JSON.
   - `UseEnumNumbers: true`: Emits numeric integer values for enum fields rather than string names.
   - `Multiline: true` and `Indent`: Produces indented multiline JSON output.

3. **UnmarshalOptions**:
   - `DiscardUnknown: true`: Discards unknown fields during unmarshaling rather than returning an error.

4. **Well-Known Types Representation**:
   - `google.protobuf.Timestamp`: Serialized as an RFC 3339 formatted string (e.g. `"2026-09-01T06:00:00Z"`).
   - `google.protobuf.Duration`: Serialized as a seconds string with trailing `"s"` (e.g. `"90s"`).
   - `google.protobuf.Struct`: Serialized directly as a native JSON object.
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 google.golang.org/protobuf/encoding/protojson in pkg:golang/google.golang.org/protobuf@v1.32.0
Kind: HOW

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

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:ee86c2cb127778160fca66cf16048ac5a9a6f27e376a3c0811fc2281bfc7c4d4","contract":["protojson.Marshal and protojson.Unmarshal roundtrip message fields with camelCase naming for fields, string representation for enums, and string representation for 64-bit integers.","protojson.MarshalOptions.UseProtoNames outputs original protobuf snake_case field names instead of camelCase.","protojson.MarshalOptions.EmitUnpopulated includes unpopulated fields with default zero values in the resulting JSON output.","protojson.MarshalOptions.UseEnumNumbers outputs integer numbers for enum fields instead of string enum names.","protojson.UnmarshalOptions.DiscardUnknown ignores unknown fields in JSON payload when true and returns an error when false.","protojson formats Google well-known types (Timestamp as RFC 3339 string, Duration as second string suffix, and Struct/Value as JSON objects)."],"goal":"verify google.golang.org/protobuf/encoding/protojson in pkg:golang/google.golang.org/protobuf@v1.32.0","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.32.0"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/encoding/protojson"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/protobuf@v1.32.0"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.32.0","symbols":["google.golang.org/protobuf/encoding/protojson"],"verifierAdapter":"golang@1"}
go.mod
module example.com/protojson

go 1.22

require google.golang.org/protobuf v1.32.0
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.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
protojson_test.go
package main

import (
	"encoding/json"
	"strings"
	"testing"
	"time"

	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/reflect/protodesc"
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/types/descriptorpb"
	"google.golang.org/protobuf/types/dynamicpb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func buildUserMessageDescriptor(t *testing.T) (protoreflect.MessageDescriptor, protoreflect.EnumDescriptor) {
	t.Helper()
	fd := &descriptorpb.FileDescriptorProto{
		Name:    proto.String("sample.proto"),
		Syntax:  proto.String("proto3"),
		Package: proto.String("sample"),
		MessageType: []*descriptorpb.DescriptorProto{
			{
				Name: proto.String("User"),
				Field: []*descriptorpb.FieldDescriptorProto{
					{
						Name:     proto.String("user_id"),
						Number:   proto.Int32(1),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_INT64.Enum(),
						JsonName: proto.String("userId"),
					},
					{
						Name:     proto.String("display_name"),
						Number:   proto.Int32(2),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
						JsonName: proto.String("displayName"),
					},
					{
						Name:     proto.String("role"),
						Number:   proto.Int32(3),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_ENUM.Enum(),
						TypeName: proto.String(".sample.Role"),
						JsonName: proto.String("role"),
					},
					{
						Name:     proto.String("tags"),
						Number:   proto.Int32(4),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
						JsonName: proto.String("tags"),
					},
					{
						Name:     proto.String("is_active"),
						Number:   proto.Int32(5),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_BOOL.Enum(),
						JsonName: proto.String("isActive"),
					},
				},
			},
		},
		EnumType: []*descriptorpb.EnumDescriptorProto{
			{
				Name: proto.String("Role"),
				Value: []*descriptorpb.EnumValueDescriptorProto{
					{Name: proto.String("ROLE_UNSPECIFIED"), Number: proto.Int32(0)},
					{Name: proto.String("ROLE_ADMIN"), Number: proto.Int32(1)},
					{Name: proto.String("ROLE_MEMBER"), Number: proto.Int32(2)},
				},
			},
		},
	}

	files, err := protodesc.NewFiles(&descriptorpb.FileDescriptorSet{File: []*descriptorpb.FileDescriptorProto{fd}})
	if err != nil {
		t.Fatalf("failed to construct dynamic proto file descriptors: %v", err)
	}

	desc, err := files.FindDescriptorByName("sample.User")
	if err != nil {
		t.Fatalf("failed to find User message descriptor: %v", err)
	}
	msgDesc, ok := desc.(protoreflect.MessageDescriptor)
	if !ok {
		t.Fatalf("sample.User descriptor is not protoreflect.MessageDescriptor")
	}

	enumDescRaw, err := files.FindDescriptorByName("sample.Role")
	if err != nil {
		t.Fatalf("failed to find Role enum descriptor: %v", err)
	}
	enumDesc, ok := enumDescRaw.(protoreflect.EnumDescriptor)
	if !ok {
		t.Fatalf("sample.Role descriptor is not protoreflect.EnumDescriptor")
	}

	return msgDesc, enumDesc
}

func TestProtojsonMarshalUnmarshalRoundtrip(t *testing.T) {
	msgDesc, enumDesc := buildUserMessageDescriptor(t)

	msg := dynamicpb.NewMessage(msgDesc)
	msg.Set(msgDesc.Fields().ByName("user_id"), protoreflect.ValueOfInt64(42))
	msg.Set(msgDesc.Fields().ByName("display_name"), protoreflect.ValueOfString("Alice"))
	msg.Set(msgDesc.Fields().ByName("role"), protoreflect.ValueOfEnum(enumDesc.Values().ByName("ROLE_ADMIN").Number()))

	tagsList := msg.Mutable(msgDesc.Fields().ByName("tags")).List()
	tagsList.Append(protoreflect.ValueOfString("admin"))
	tagsList.Append(protoreflect.ValueOfString("engineering"))

	// Marshal to JSON using default protojson.Marshal
	jsonBytes, err := protojson.Marshal(msg)
	if err != nil {
		t.Fatalf("protojson.Marshal failed: %v", err)
	}

	// Verify standard camelCase JSON field names and string enum representation
	var parsed map[string]any
	if err := json.Unmarshal(jsonBytes, &parsed); err != nil {
		t.Fatalf("json.Unmarshal failed to parse protojson output: %v", err)
	}

	if parsed["userId"] != "42" && parsed["userId"] != float64(42) {
		// In proto3 JSON specification, 64-bit integers are marshaled as strings
		if parsed["userId"] != "42" {
			t.Fatalf("expected userId to be string '42' or number 42, got %v", parsed["userId"])
		}
	}
	if parsed["displayName"] != "Alice" {
		t.Fatalf("expected displayName to be 'Alice', got %v", parsed["displayName"])
	}
	if parsed["role"] != "ROLE_ADMIN" {
		t.Fatalf("expected role to be 'ROLE_ADMIN', got %v", parsed["role"])
	}

	// Unmarshal into a new message and verify equality
	unmarshaled := dynamicpb.NewMessage(msgDesc)
	if err := protojson.Unmarshal(jsonBytes, unmarshaled); err != nil {
		t.Fatalf("protojson.Unmarshal failed: %v", err)
	}

	if !proto.Equal(msg, unmarshaled) {
		t.Fatalf("unmarshaled message does not match original: got %v, want %v", unmarshaled, msg)
	}
}

func TestProtojsonMarshalOptionsUseProtoNames(t *testing.T) {
	msgDesc, _ := buildUserMessageDescriptor(t)

	msg := dynamicpb.NewMessage(msgDesc)
	msg.Set(msgDesc.Fields().ByName("user_id"), protoreflect.ValueOfInt64(100))
	msg.Set(msgDesc.Fields().ByName("display_name"), protoreflect.ValueOfString("Bob"))

	// Default opts (UseProtoNames: false) uses camelCase
	defaultJson, err := protojson.Marshal(msg)
	if err != nil {
		t.Fatalf("protojson.Marshal failed: %v", err)
	}
	if !strings.Contains(string(defaultJson), `"displayName"`) {
		t.Fatalf("expected camelCase 'displayName' in default JSON output: %s", string(defaultJson))
	}

	// With UseProtoNames: true, uses snake_case proto field names
	opts := protojson.MarshalOptions{
		UseProtoNames: true,
	}
	protoNameJson, err := opts.Marshal(msg)
	if err != nil {
		t.Fatalf("opts.Marshal failed: %v", err)
	}
	if !strings.Contains(string(protoNameJson), `"display_name"`) {
		t.Fatalf("expected proto name 'display_name' with UseProtoNames=true: %s", string(protoNameJson))
	}
	if strings.Contains(string(protoNameJson), `"displayName"`) {
		t.Fatalf("unexpected camelCase 'displayName' with UseProtoNames=true: %s", string(protoNameJson))
	}
}

func TestProtojsonMarshalOptionsEmitUnpopulated(t *testing.T) {
	msgDesc, _ := buildUserMessageDescriptor(t)

	// Message with only user_id set; display_name, role, tags, is_active unpopulated
	msg := dynamicpb.NewMessage(msgDesc)
	msg.Set(msgDesc.Fields().ByName("user_id"), protoreflect.ValueOfInt64(7))

	// Default: unpopulated fields omitted
	defaultJson, err := protojson.Marshal(msg)
	if err != nil {
		t.Fatalf("protojson.Marshal failed: %v", err)
	}
	if strings.Contains(string(defaultJson), `"displayName"`) || strings.Contains(string(defaultJson), `"isActive"`) {
		t.Fatalf("default protojson.Marshal should omit unpopulated fields: %s", string(defaultJson))
	}

	// EmitUnpopulated: true emits zero values for unpopulated fields
	opts := protojson.MarshalOptions{
		EmitUnpopulated: true,
	}
	unpopulatedJson, err := opts.Marshal(msg)
	if err != nil {
		t.Fatalf("opts.Marshal with EmitUnpopulated failed: %v", err)
	}

	var parsed map[string]any
	if err := json.Unmarshal(unpopulatedJson, &parsed); err != nil {
		t.Fatalf("failed to parse JSON with EmitUnpopulated: %v", err)
	}

	if parsed["displayName"] != "" {
		t.Fatalf("expected displayName to be empty string, got %v", parsed["displayName"])
	}
	if parsed["isActive"] != false {
		t.Fatalf("expected isActive to be false, got %v", parsed["isActive"])
	}
	if parsed["role"] != "ROLE_UNSPECIFIED" {
		t.Fatalf("expected role to be default enum 'ROLE_UNSPECIFIED', got %v", parsed["role"])
	}
}

func TestProtojsonMarshalOptionsUseEnumNumbers(t *testing.T) {
	msgDesc, enumDesc := buildUserMessageDescriptor(t)

	msg := dynamicpb.NewMessage(msgDesc)
	msg.Set(msgDesc.Fields().ByName("role"), protoreflect.ValueOfEnum(enumDesc.Values().ByName("ROLE_ADMIN").Number()))

	opts := protojson.MarshalOptions{
		UseEnumNumbers: true,
	}
	enumNumJson, err := opts.Marshal(msg)
	if err != nil {
		t.Fatalf("opts.Marshal with UseEnumNumbers failed: %v", err)
	}

	var parsed map[string]any
	if err := json.Unmarshal(enumNumJson, &parsed); err != nil {
		t.Fatalf("failed to parse enum number JSON: %v", err)
	}

	// ROLE_ADMIN has number 1
	if parsed["role"] != float64(1) {
		t.Fatalf("expected role to be integer 1, got %v", parsed["role"])
	}
}

func TestProtojsonUnmarshalOptionsDiscardUnknown(t *testing.T) {
	msgDesc, _ := buildUserMessageDescriptor(t)

	rawJson := `{"userId": "123", "displayName": "Charlie", "unknownField": "should_fail_or_discard"}`

	// Default unmarshal fails on unknown field
	msgDefault := dynamicpb.NewMessage(msgDesc)
	err := protojson.Unmarshal([]byte(rawJson), msgDefault)
	if err == nil {
		t.Fatalf("expected protojson.Unmarshal to fail on unknown field by default")
	}

	// DiscardUnknown: true succeeds and ignores unknown field
	opts := protojson.UnmarshalOptions{
		DiscardUnknown: true,
	}
	msgDiscard := dynamicpb.NewMessage(msgDesc)
	if err := opts.Unmarshal([]byte(rawJson), msgDiscard); err != nil {
		t.Fatalf("opts.Unmarshal with DiscardUnknown=true should succeed, got error: %v", err)
	}

	if msgDiscard.Get(msgDesc.Fields().ByName("display_name")).String() != "Charlie" {
		t.Fatalf("expected displayName 'Charlie', got %s", msgDiscard.Get(msgDesc.Fields().ByName("display_name")).String())
	}
}

func TestProtojsonWellKnownTypesFormatting(t *testing.T) {
	// Timestamp formatting as RFC 3339 string
	ts := timestamppb.New(time.Date(2026, 9, 1, 6, 0, 0, 0, time.UTC))
	tsJson, err := protojson.Marshal(ts)
	if err != nil {
		t.Fatalf("protojson.Marshal timestamppb failed: %v", err)
	}
	expectedTs := `"2026-09-01T06:00:00Z"`
	if string(tsJson) != expectedTs {
		t.Fatalf("expected timestamp JSON %s, got %s", expectedTs, string(tsJson))
	}

	// Duration formatting as seconds string with suffix 's'
	dur := durationpb.New(90 * time.Second)
	durJson, err := protojson.Marshal(dur)
	if err != nil {
		t.Fatalf("protojson.Marshal durationpb failed: %v", err)
	}
	if string(durJson) != `"90s"` {
		t.Fatalf("expected duration JSON '\"90s\"', got %s", string(durJson))
	}

	// Structpb / Value dynamic json object representation
	st, err := structpb.NewStruct(map[string]any{
		"key":    "value",
		"number": 123.45,
		"flag":   true,
	})
	if err != nil {
		t.Fatalf("structpb.NewStruct failed: %v", err)
	}
	stJson, err := protojson.Marshal(st)
	if err != nil {
		t.Fatalf("protojson.Marshal structpb failed: %v", err)
	}
	var stMap map[string]any
	if err := json.Unmarshal(stJson, &stMap); err != nil {
		t.Fatalf("failed to parse structpb JSON: %v", err)
	}
	if stMap["key"] != "value" || stMap["number"] != 123.45 || stMap["flag"] != true {
		t.Fatalf("unexpected structpb JSON content: %v", stMap)
	}
}

func TestProtojsonFormatDeterministicOutput(t *testing.T) {
	ts := timestamppb.New(time.Date(2026, 9, 1, 6, 0, 0, 0, time.UTC))
	formatted := protojson.Format(ts)
	if formatted != `"2026-09-01T06:00:00Z"` {
		t.Fatalf("protojson.Format returned unexpected string: %s", formatted)
	}

	// Multiline formatting with Indent
	st, _ := structpb.NewStruct(map[string]any{"a": 1})
	opts := protojson.MarshalOptions{
		Multiline: true,
		Indent:    "  ",
	}
	multiJson, err := opts.Marshal(st)
	if err != nil {
		t.Fatalf("opts.Marshal multiline failed: %v", err)
	}
	if !strings.Contains(string(multiJson), "\n") || !strings.Contains(string(multiJson), "  ") {
		t.Fatalf("expected multiline indented output: %s", string(multiJson))
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/encoding/protojson in pkg:golang/google.golang.org/protobuf@v1.32.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.32.0"
  ],
  "symbols": [
    "google.golang.org/protobuf/encoding/protojson"
  ]
}

오리진 시더

익명