CodeSampleX

샘플

github.com/go-logfmt/logfmt v0.5.0: Encoder.EncodeKeyvals

검증된 샘플 — golang github.com/go-logfmt/logfmt v0.5.0: Encoder.EncodeKeyvals. go 1.26 · linux debian/x64 · docker에서 contract를 실행해 통과했습니다.

sha256:91d323d7593cc9bed017e26d0fe246c94f0fa2980ee29451c8c1a300e2aca2ae

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

케이스

HOW
목표
verify pkg:golang/github.com/go-logfmt/logfmt@v0.5.0
패키지
심벌
  • github.com/go-logfmt/logfmt.Encoder.EncodeKeyvals
생성일
2026-09-03T18:55:56Z

컨트랙트

  1. logfmt.Encoder.EncodeKeyvals writes variadic key-value pairs formatted as key=value separated by spaces without trailing newline
  2. logfmt.Encoder.EncodeKeyvals appends key-value pairs across multiple sequential calls with space separators on the same record
  3. logfmt.Encoder.EncodeKeyvals handles odd number of arguments by appending a null value
  4. logfmt.Encoder.EncodeKeyvals skips keys of unsupported types along with their corresponding values
  5. logfmt.Encoder.EncodeKeyvals replaces values of unsupported type or marshaler errors with their error string instead of failing
  6. logfmt.Encoder.Reset clears the separator state so subsequent EncodeKeyvals begins without a leading space
  7. logfmt.Encoder.EncodeKeyvals returns ErrNilKey on nil key and ErrInvalidKey on keys with only invalid runes

파일

  • 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 pkg:golang/github.com/go-logfmt/logfmt@v0.5.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/go-logfmt/logfmt@v0.5.0
Demonstrate these symbols/APIs:
  - github.com/go-logfmt/logfmt.Encoder.EncodeKeyvals

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:d58001a9b33389066a483f3af0a08e28577b878c9590470b696b8ca3683c2b37","contract":["logfmt.Encoder.EncodeKeyvals writes variadic key-value pairs formatted as key=value separated by spaces without trailing newline","logfmt.Encoder.EncodeKeyvals appends key-value pairs across multiple sequential calls with space separators on the same record","logfmt.Encoder.EncodeKeyvals handles odd number of arguments by appending a null value","logfmt.Encoder.EncodeKeyvals skips keys of unsupported types along with their corresponding values","logfmt.Encoder.EncodeKeyvals replaces values of unsupported type or marshaler errors with their error string instead of failing","logfmt.Encoder.Reset clears the separator state so subsequent EncodeKeyvals begins without a leading space","logfmt.Encoder.EncodeKeyvals returns ErrNilKey on nil key and ErrInvalidKey on keys with only invalid runes"],"goal":"verify pkg:golang/github.com/go-logfmt/logfmt@v0.5.0","kind":"HOW","packages":["pkg:golang/github.com/go-logfmt/logfmt@v0.5.0"],"schemaVersion":1,"symbols":["github.com/go-logfmt/logfmt.Encoder.EncodeKeyvals"]},"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/github.com/go-logfmt/logfmt@v0.5.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/go-logfmt/logfmt@v0.5.0","symbols":["github.com/go-logfmt/logfmt.Encoder.EncodeKeyvals"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/go-logfmt/logfmt v0.5.0
go.sum
github.com/go-logfmt/logfmt v0.5.0 h1:TrB8swr/68K7m9CcGut2g3UOihhbcbiMAYiuTXdEih4=
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
sample.go
package sample

import (
	"bytes"
	"io"

	"github.com/go-logfmt/logfmt"
)

// BatchEncoder provides structured logging helpers wrapping logfmt.Encoder.
type BatchEncoder struct {
	buf bytes.Buffer
	enc *logfmt.Encoder
}

// NewBatchEncoder initializes a new BatchEncoder.
func NewBatchEncoder() *BatchEncoder {
	b := &BatchEncoder{}
	b.enc = logfmt.NewEncoder(&b.buf)
	return b
}

// AppendKeyvals appends variadic key-value pairs to the current log buffer.
func (b *BatchEncoder) AppendKeyvals(keyvals ...interface{}) error {
	return b.enc.EncodeKeyvals(keyvals...)
}

// Bytes returns the encoded bytes in the buffer.
func (b *BatchEncoder) Bytes() []byte {
	return b.buf.Bytes()
}

// String returns the encoded logfmt record as a string.
func (b *BatchEncoder) String() string {
	return b.buf.String()
}

// Reset clears the buffer and resets the encoder state.
func (b *BatchEncoder) Reset() {
	b.buf.Reset()
	b.enc.Reset()
}

// EncodeRecord encodes keyvals into w and terminates the record with a newline.
func EncodeRecord(w io.Writer, keyvals ...interface{}) error {
	enc := logfmt.NewEncoder(w)
	if err := enc.EncodeKeyvals(keyvals...); err != nil {
		return err
	}
	return enc.EndRecord()
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/go-logfmt/logfmt@v0.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-logfmt/logfmt@v0.5.0"
  ],
  "symbols": [
    "github.com/go-logfmt/logfmt.Encoder.EncodeKeyvals"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"strings"

	"github.com/go-logfmt/logfmt"
	"sample"
)

type failingTextMarshaler struct{}

func (failingTextMarshaler) MarshalText() ([]byte, error) {
	return nil, errors.New("marshaler failure")
}

func main() {
	// Assertion 1: logfmt.Encoder.EncodeKeyvals writes variadic key-value pairs formatted as key=value separated by spaces without trailing newline
	var buf1 bytes.Buffer
	enc1 := logfmt.NewEncoder(&buf1)
	if err := enc1.EncodeKeyvals("level", "info", "msg", "service started", "workers", 4); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 1 error: %v\n", err)
		os.Exit(1)
	}
	expected1 := `level=info msg="service started" workers=4`
	if buf1.String() != expected1 {
		fmt.Fprintf(os.Stderr, "assertion 1 mismatch: got %q, expected %q\n", buf1.String(), expected1)
		os.Exit(1)
	}
	if bytes.HasSuffix(buf1.Bytes(), []byte("\n")) {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: EncodeKeyvals should not append a newline\n")
		os.Exit(1)
	}

	// Assertion 2: logfmt.Encoder.EncodeKeyvals appends key-value pairs across multiple sequential calls with space separators on the same record
	var buf2 bytes.Buffer
	enc2 := logfmt.NewEncoder(&buf2)
	if err := enc2.EncodeKeyvals("step", 1); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 2 call 1 error: %v\n", err)
		os.Exit(1)
	}
	if err := enc2.EncodeKeyvals("step", 2, "status", "ok"); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 2 call 2 error: %v\n", err)
		os.Exit(1)
	}
	expected2 := "step=1 step=2 status=ok"
	if buf2.String() != expected2 {
		fmt.Fprintf(os.Stderr, "assertion 2 mismatch: got %q, expected %q\n", buf2.String(), expected2)
		os.Exit(1)
	}

	// Assertion 3: logfmt.Encoder.EncodeKeyvals handles odd number of arguments by appending a null value
	var buf3 bytes.Buffer
	enc3 := logfmt.NewEncoder(&buf3)
	if err := enc3.EncodeKeyvals("action", "test", "dangling"); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 3 error: %v\n", err)
		os.Exit(1)
	}
	expected3 := "action=test dangling=null"
	if buf3.String() != expected3 {
		fmt.Fprintf(os.Stderr, "assertion 3 mismatch: got %q, expected %q\n", buf3.String(), expected3)
		os.Exit(1)
	}

	// Assertion 4: logfmt.Encoder.EncodeKeyvals skips keys of unsupported types along with their corresponding values
	var buf4 bytes.Buffer
	enc4 := logfmt.NewEncoder(&buf4)
	unsupportedKeyMap := map[string]int{"k": 1}
	unsupportedKeySlice := []string{"unsupported"}
	if err := enc4.EncodeKeyvals(unsupportedKeyMap, "val1", "validKey", "validVal", unsupportedKeySlice, "val2"); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 4 error: %v\n", err)
		os.Exit(1)
	}
	expected4 := "validKey=validVal"
	if buf4.String() != expected4 {
		fmt.Fprintf(os.Stderr, "assertion 4 mismatch: got %q, expected %q\n", buf4.String(), expected4)
		os.Exit(1)
	}

	// Assertion 5: logfmt.Encoder.EncodeKeyvals replaces values of unsupported type or marshaler errors with their error string instead of failing
	var buf5 bytes.Buffer
	enc5 := logfmt.NewEncoder(&buf5)
	unsupportedVal := struct{ Field string }{Field: "test"}
	if err := enc5.EncodeKeyvals("unsupportedVal", unsupportedVal, "badMarshal", failingTextMarshaler{}); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 5 error: %v\n", err)
		os.Exit(1)
	}
	got5 := buf5.String()
	if !strings.Contains(got5, `unsupportedVal="unsupported value type"`) {
		fmt.Fprintf(os.Stderr, "assertion 5 missing unsupported value type error: got %q\n", got5)
		os.Exit(1)
	}
	if !strings.Contains(got5, `badMarshal="error marshaling value of type main.failingTextMarshaler: marshaler failure"`) {
		fmt.Fprintf(os.Stderr, "assertion 5 missing marshaler error: got %q\n", got5)
		os.Exit(1)
	}

	// Assertion 6: logfmt.Encoder.Reset clears the separator state so subsequent EncodeKeyvals begins without a leading space
	var buf6 bytes.Buffer
	enc6 := logfmt.NewEncoder(&buf6)
	if err := enc6.EncodeKeyvals("first", "record"); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 6 encode 1 error: %v\n", err)
		os.Exit(1)
	}
	buf6.Reset()
	enc6.Reset()
	if err := enc6.EncodeKeyvals("second", "record"); err != nil {
		fmt.Fprintf(os.Stderr, "assertion 6 encode 2 error: %v\n", err)
		os.Exit(1)
	}
	if buf6.String() != "second=record" {
		fmt.Fprintf(os.Stderr, "assertion 6 mismatch after reset: got %q, expected %q\n", buf6.String(), "second=record")
		os.Exit(1)
	}

	// Assertion 7: logfmt.Encoder.EncodeKeyvals returns ErrNilKey on nil key and ErrInvalidKey on keys with only invalid runes
	var buf7 bytes.Buffer
	enc7 := logfmt.NewEncoder(&buf7)
	errNil := enc7.EncodeKeyvals(nil, "val")
	if !errors.Is(errNil, logfmt.ErrNilKey) {
		fmt.Fprintf(os.Stderr, "assertion 7 expected ErrNilKey, got: %v\n", errNil)
		os.Exit(1)
	}
	errInvalid := enc7.EncodeKeyvals("   ", "val")
	if !errors.Is(errInvalid, logfmt.ErrInvalidKey) {
		fmt.Fprintf(os.Stderr, "assertion 7 expected ErrInvalidKey for whitespace, got: %v\n", errInvalid)
		os.Exit(1)
	}

	// Helper verification using sample package
	batch := sample.NewBatchEncoder()
	if err := batch.AppendKeyvals("component", "auth", "duration_ms", 12); err != nil {
		fmt.Fprintf(os.Stderr, "helper AppendKeyvals error: %v\n", err)
		os.Exit(1)
	}
	if batch.String() != "component=auth duration_ms=12" {
		fmt.Fprintf(os.Stderr, "helper batch mismatch: got %q\n", batch.String())
		os.Exit(1)
	}

	var recBuf bytes.Buffer
	if err := sample.EncodeRecord(&recBuf, "event", "login", "user", "alice"); err != nil {
		fmt.Fprintf(os.Stderr, "helper EncodeRecord error: %v\n", err)
		os.Exit(1)
	}
	if recBuf.String() != "event=login user=alice\n" {
		fmt.Fprintf(os.Stderr, "helper EncodeRecord mismatch: got %q\n", recBuf.String())
		os.Exit(1)
	}

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

오리진 시더

익명