CodeSampleX

샘플

google.golang.org/protobuf v1.28.0: structpb.NewStruct

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

sha256:145af0919f2ab55c3c067a6fd76cff1fc9d8dfc44c119f90979e3011f16c256c

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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 google.golang.org/protobuf/types/known/structpb.NewStruct in pkg:golang/google.golang.org/protobuf@v1.28.0
패키지
심벌
  • google.golang.org/protobuf/types/known/structpb.NewStruct
생성일
2026-09-02T06:55:19Z

컨트랙트

  1. structpb.NewStruct converts Go maps into *structpb.Struct, and Struct.AsMap converts it back to map[string]interface{}, while calling AsMap on a nil receiver safely returns an empty non-nil map.
  2. structpb.NewStruct handles empty maps and nil maps, returning an empty Struct.
  3. structpb.NewStruct recursively converts nested map and slice structures into nested Struct and ListValue messages.
  4. structpb.NewStruct returns an error when passed maps containing unsupported Go types such as channels or functions.
  5. structpb.Struct supports proto binary wire serialization and protojson serialization formatting as a standard JSON object.

파일

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

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

소스

NOTES.md
# Protocol Buffers structpb.NewStruct Map Conversion

A search for `google.golang.org/protobuf/types/known/structpb.NewStruct` in `google.golang.org/protobuf@v1.28.0` required verification against the target package version.

This sample tests and verifies conversion semantics between dynamic Go maps and Protocol Buffers `Struct` messages using `structpb.NewStruct`.

## Observed Behavior

1. **Map Conversion (`structpb.NewStruct` & `Struct.AsMap`)**:
   - `structpb.NewStruct(map[string]interface{})` converts Go maps to `*structpb.Struct`.
   - `st.AsMap()` extracts the values back into a `map[string]interface{}`.
   - Calling `AsMap()` on a `nil` receiver safely returns an empty non-nil `map[string]interface{}{}` without panicking.
   - `structpb.NewStruct(nil)` and `structpb.NewStruct(map[string]interface{}{})` succeed and return an empty `Struct`.

2. **Recursive Nested Map and Slice Unpacking**:
   - `structpb.NewStruct` recursively converts nested maps and slices into nested `Struct` and `ListValue` protobuf messages, and `AsMap()` roundtrips the structure back to native Go types.

3. **Error Handling on Unsupported Types**:
   - Types that cannot be represented in JSON / protobuf Struct (e.g., channels, functions) return an error when passed in a map to `structpb.NewStruct`.

4. **Serialization & Interoperability**:
   - `structpb.Struct` supports both binary protobuf wire serialization (`proto.Marshal` / `proto.Unmarshal`) and canonical JSON serialization (`protojson.Marshal` / `protojson.Unmarshal`), serializing directly as a standard 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/types/known/structpb.NewStruct in pkg:golang/google.golang.org/protobuf@v1.28.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.28.0
Demonstrate these symbols/APIs:
  - google.golang.org/protobuf/types/known/structpb.NewStruct

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:fe026cc0937c2c79458ba1d21f19cf2caa1eebb308f68402c81f8f7c0b4ee839","contract":["structpb.NewStruct converts Go maps into *structpb.Struct, and Struct.AsMap converts it back to map[string]interface{}, while calling AsMap on a nil receiver safely returns an empty non-nil map.","structpb.NewStruct handles empty maps and nil maps, returning an empty Struct.","structpb.NewStruct recursively converts nested map and slice structures into nested Struct and ListValue messages.","structpb.NewStruct returns an error when passed maps containing unsupported Go types such as channels or functions.","structpb.Struct supports proto binary wire serialization and protojson serialization formatting as a standard JSON object."],"goal":"verify google.golang.org/protobuf/types/known/structpb.NewStruct in pkg:golang/google.golang.org/protobuf@v1.28.0","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.28.0"],"schemaVersion":1,"symbols":["google.golang.org/protobuf/types/known/structpb.NewStruct"]},"contractCommand":["go","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.28.0"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.28.0","symbols":["google.golang.org/protobuf/types/known/structpb.NewStruct"],"verifierAdapter":"golang@1"}
go.mod
module example.com/structpbdemo

go 1.23

require google.golang.org/protobuf v1.28.0
go.sum
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.28.0 h1:w43yiav+6bVFTBQFZX0r7ipe9JQ1QsbMgHwbBziscLw=
google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify google.golang.org/protobuf/types/known/structpb.NewStruct in pkg:golang/google.golang.org/protobuf@v1.28.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.28.0"
  ],
  "symbols": [
    "google.golang.org/protobuf/types/known/structpb.NewStruct"
  ]
}
structpb_test.go
package structpbdemo_test

import (
	"reflect"
	"testing"

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

// TestStructPBNewStructMapConversion verifies structpb.NewStruct converts Go maps to *structpb.Struct
// and Struct.AsMap converts it back to map[string]interface{}.
func TestStructPBNewStructMapConversion(t *testing.T) {
	inputMap := map[string]interface{}{
		"name":    "service-config",
		"port":    float64(8080),
		"enabled": true,
		"tags":    []interface{}{"api", "gateway"},
		"extra":   nil,
	}

	st, err := structpb.NewStruct(inputMap)
	if err != nil {
		t.Fatalf("NewStruct failed: %v", err)
	}

	if st.Fields == nil {
		t.Fatalf("expected non-nil Fields in Struct")
	}

	if nameVal := st.Fields["name"].GetStringValue(); nameVal != "service-config" {
		t.Errorf("expected name to be 'service-config', got %q", nameVal)
	}
	if portVal := st.Fields["port"].GetNumberValue(); portVal != 8080 {
		t.Errorf("expected port to be 8080, got %v", portVal)
	}
	if enabledVal := st.Fields["enabled"].GetBoolValue(); !enabledVal {
		t.Errorf("expected enabled to be true, got %v", enabledVal)
	}

	outputMap := st.AsMap()
	if !reflect.DeepEqual(inputMap, outputMap) {
		t.Fatalf("AsMap() mismatch:\nwant: %#v\ngot:  %#v", inputMap, outputMap)
	}
}

// TestStructPBNewStructNilAndEmpty verifies structpb.NewStruct behavior on nil and empty maps,
// as well as nil receiver safety for AsMap.
func TestStructPBNewStructNilAndEmpty(t *testing.T) {
	// Empty struct from nil map
	emptyStruct, err := structpb.NewStruct(nil)
	if err != nil {
		t.Fatalf("NewStruct(nil) failed: %v", err)
	}
	if len(emptyStruct.AsMap()) != 0 {
		t.Fatalf("expected empty map for NewStruct(nil), got %#v", emptyStruct.AsMap())
	}

	// Empty struct from empty map
	emptyMapStruct, err := structpb.NewStruct(map[string]interface{}{})
	if err != nil {
		t.Fatalf("NewStruct(empty) failed: %v", err)
	}
	if len(emptyMapStruct.AsMap()) != 0 {
		t.Fatalf("expected empty map for NewStruct(empty), got %#v", emptyMapStruct.AsMap())
	}

	// Nil struct safety: calling AsMap() on nil receiver safely returns empty map (not nil)
	var nilStruct *structpb.Struct
	if got := nilStruct.AsMap(); got == nil || len(got) != 0 {
		t.Fatalf("expected nilStruct.AsMap() to return empty non-nil map, got %#v", got)
	}
}

// TestStructPBNewStructNestedData verifies nested struct and list value conversions via structpb.NewStruct.
func TestStructPBNewStructNestedData(t *testing.T) {
	nestedData := map[string]interface{}{
		"service": "payments",
		"config": map[string]interface{}{
			"retries": float64(5),
			"debug":   false,
		},
		"endpoints": []interface{}{
			"https://example.com/v1",
			"https://example.com/v2",
		},
	}

	st, err := structpb.NewStruct(nestedData)
	if err != nil {
		t.Fatalf("NewStruct(nestedData) failed: %v", err)
	}

	outputMap := st.AsMap()
	if !reflect.DeepEqual(nestedData, outputMap) {
		t.Fatalf("AsMap() mismatch on nested data:\nwant: %#v\ngot:  %#v", nestedData, outputMap)
	}
}

// TestStructPBNewStructUnsupportedTypesError verifies structpb.NewStruct returns an error
// when given maps containing unsupported Go types (e.g. channels, funcs).
func TestStructPBNewStructUnsupportedTypesError(t *testing.T) {
	ch := make(chan int)
	invalidMap := map[string]interface{}{
		"invalid_chan": ch,
	}
	if _, err := structpb.NewStruct(invalidMap); err == nil {
		t.Fatalf("expected error when calling NewStruct with channel value, got nil")
	}

	fn := func() {}
	invalidMapFn := map[string]interface{}{
		"invalid_fn": fn,
	}
	if _, err := structpb.NewStruct(invalidMapFn); err == nil {
		t.Fatalf("expected error when calling NewStruct with func value, got nil")
	}
}

// TestStructPBNewStructProtoAndJSONSerialization verifies proto wire and JSON serialization of structpb.Struct.
func TestStructPBNewStructProtoAndJSONSerialization(t *testing.T) {
	data := map[string]interface{}{
		"env":     "production",
		"retries": float64(3),
		"verbose": false,
	}

	st, err := structpb.NewStruct(data)
	if err != nil {
		t.Fatalf("NewStruct failed: %v", err)
	}

	// 1. Proto wire serialization
	wireBytes, err := proto.Marshal(st)
	if err != nil {
		t.Fatalf("proto.Marshal failed: %v", err)
	}

	unmarshaledSt := &structpb.Struct{}
	if err := proto.Unmarshal(wireBytes, unmarshaledSt); err != nil {
		t.Fatalf("proto.Unmarshal failed: %v", err)
	}

	if !proto.Equal(st, unmarshaledSt) {
		t.Fatalf("proto.Unmarshal result differs from original")
	}

	// 2. protojson serialization produces canonical JSON representation
	jsonBytes, err := protojson.Marshal(st)
	if err != nil {
		t.Fatalf("protojson.Marshal failed: %v", err)
	}

	jsonSt := &structpb.Struct{}
	if err := protojson.Unmarshal(jsonBytes, jsonSt); err != nil {
		t.Fatalf("protojson.Unmarshal failed: %v", err)
	}

	if !proto.Equal(st, jsonSt) {
		t.Fatalf("protojson roundtrip mismatch")
	}
}

오리진 시더

익명