CodeSampleX

Exemplo

github.com/go-logfmt/logfmt v0.6.0: NewEncoder

Amostra verificada para golang github.com/go-logfmt/logfmt v0.6.0: NewEncoder. O contrato rodou em go 1.26 · linux debian/x64 · docker e passou.

sha256:0b4a1385a998a94965164dc2afbbee1f121fdbb15fd343cf55494a987c281648

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
verify logfmt.NewEncoder in pkg:golang/github.com/go-logfmt/logfmt@v0.6.0
Pacotes
Símbolos
  • logfmt.NewEncoder
Ambiente
go 1.26.6
Criado
2026-09-02T01:59:42Z

Contrato

  1. logfmt.NewEncoder creates an Encoder writing logfmt formatted records to an io.Writer
  2. Encoder.EncodeKeyval encodes individual key=value pairs and EndRecord appends a newline
  3. Encoder.EncodeKeyvals encodes alternating key-value pairs without trailing newline until EndRecord, and serializes odd trailing keys with a null value
  4. Values with spaces, equals, or quotes are quoted with escape characters, and empty string values are formatted as key=
  5. Encoder returns ErrNilKey for nil keys, ErrInvalidKey for empty or stripped-only keys, and ErrUnsupportedKeyType for unsupported key types
  6. Encoder returns ErrUnsupportedValueType when attempting to serialize unsupported value types
  7. fmt.Stringer implementations are supported as valid keys and values
  8. Encoder.Reset clears encoder error state allowing subsequent encoding operations

Arquivos

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.go
  • spec.json
  • test/contract.go

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/go-logfmt/logfmt@v0.6.0
Demonstrate these symbols/APIs:
  - logfmt.NewEncoder
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:3ef17b99d6d5bc24934226f6473b1174eb0383533983d47e5e4b29a0a0d48c35","contract":["logfmt.NewEncoder creates an Encoder writing logfmt formatted records to an io.Writer","Encoder.EncodeKeyval encodes individual key=value pairs and EndRecord appends a newline","Encoder.EncodeKeyvals encodes alternating key-value pairs without trailing newline until EndRecord, and serializes odd trailing keys with a null value","Values with spaces, equals, or quotes are quoted with escape characters, and empty string values are formatted as key=","Encoder returns ErrNilKey for nil keys, ErrInvalidKey for empty or stripped-only keys, and ErrUnsupportedKeyType for unsupported key types","Encoder returns ErrUnsupportedValueType when attempting to serialize unsupported value types","fmt.Stringer implementations are supported as valid keys and values","Encoder.Reset clears encoder error state allowing subsequent encoding operations"],"goal":"verify logfmt.NewEncoder in pkg:golang/github.com/go-logfmt/logfmt@v0.6.0","kind":"HOW","packages":["pkg:golang/github.com/go-logfmt/logfmt@v0.6.0"],"schemaVersion":1,"symbols":["logfmt.NewEncoder"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","moduleSystem":"go.mod","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/go-logfmt/logfmt@v0.6.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/go-logfmt/logfmt@v0.6.0","symbols":["logfmt.NewEncoder"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.22

require github.com/go-logfmt/logfmt v0.6.0
go.sum
github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4=
github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
sample.go
package sample

import (
	"io"

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

// LogEncoder wraps logfmt.Encoder to provide structured log formatting.
type LogEncoder struct {
	enc *logfmt.Encoder
}

// NewLogEncoder creates a new LogEncoder wrapping logfmt.NewEncoder.
func NewLogEncoder(w io.Writer) *LogEncoder {
	return &LogEncoder{
		enc: logfmt.NewEncoder(w),
	}
}

// EncodeEntry encodes key-value pairs into logfmt format and terminates the record.
func (l *LogEncoder) EncodeEntry(keyvals ...interface{}) error {
	if err := l.enc.EncodeKeyvals(keyvals...); err != nil {
		return err
	}
	return l.enc.EndRecord()
}

// EncodeField encodes a single key-value field without terminating the record.
func (l *LogEncoder) EncodeField(key, val interface{}) error {
	return l.enc.EncodeKeyval(key, val)
}

// EndLine terminates the current record with a newline.
func (l *LogEncoder) EndLine() error {
	return l.enc.EndRecord()
}

// Reset clears the internal encoder state.
func (l *LogEncoder) Reset() {
	l.enc.Reset()
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify logfmt.NewEncoder in pkg:golang/github.com/go-logfmt/logfmt@v0.6.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-logfmt/logfmt@v0.6.0"
  ],
  "symbols": [
    "logfmt.NewEncoder"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
test/contract.go
package main

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

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

type customStringer struct {
	val string
}

func (c customStringer) String() string {
	return c.val
}

type unsupportedType struct {
	num int
}

func main() {
	// 1. logfmt.NewEncoder creates a valid Encoder writing to an io.Writer
	var buf bytes.Buffer
	enc := logfmt.NewEncoder(&buf)
	if enc == nil {
		fmt.Fprintf(os.Stderr, "expected non-nil Encoder from logfmt.NewEncoder\n")
		os.Exit(1)
	}

	// 2. EncodeKeyval writes individual key=value pairs separated by spaces and EndRecord appends a newline
	if err := enc.EncodeKeyval("level", "info"); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeKeyval level failed: %v\n", err)
		os.Exit(1)
	}
	if err := enc.EncodeKeyval("msg", "system initialization"); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeKeyval msg failed: %v\n", err)
		os.Exit(1)
	}
	if err := enc.EncodeKeyval("status", 200); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeKeyval status failed: %v\n", err)
		os.Exit(1)
	}
	if err := enc.EndRecord(); err != nil {
		fmt.Fprintf(os.Stderr, "EndRecord failed: %v\n", err)
		os.Exit(1)
	}
	expected := "level=info msg=\"system initialization\" status=200\n"
	if buf.String() != expected {
		fmt.Fprintf(os.Stderr, "expected %q, got %q\n", expected, buf.String())
		os.Exit(1)
	}

	// 3. EncodeKeyvals writes multiple key-value pairs in a single call without trailing newline until EndRecord
	buf.Reset()
	t := time.Date(2026, 9, 2, 12, 0, 0, 0, time.UTC)
	if err := enc.EncodeKeyvals("ts", t, "user", "admin", "active", true, "unpaired"); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeKeyvals failed: %v\n", err)
		os.Exit(1)
	}
	if err := enc.EndRecord(); err != nil {
		fmt.Fprintf(os.Stderr, "EndRecord after EncodeKeyvals failed: %v\n", err)
		os.Exit(1)
	}
	expectedKeyvals := "ts=2026-09-02T12:00:00Z user=admin active=true unpaired=null\n"
	if buf.String() != expectedKeyvals {
		fmt.Fprintf(os.Stderr, "expected %q, got %q\n", expectedKeyvals, buf.String())
		os.Exit(1)
	}

	// 4. Special characters, quotes, and newlines in values are escaped; empty strings format as key=
	buf.Reset()
	if err := enc.EncodeKeyvals("quote", `he said "hello"`, "multiline", "line1\nline2", "empty", ""); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeKeyvals with special chars failed: %v\n", err)
		os.Exit(1)
	}
	if err := enc.EndRecord(); err != nil {
		fmt.Fprintf(os.Stderr, "EndRecord failed: %v\n", err)
		os.Exit(1)
	}
	out := buf.String()
	if !strings.Contains(out, `quote="he said \"hello\""`) {
		fmt.Fprintf(os.Stderr, "expected escaped quotes in output, got %q\n", out)
		os.Exit(1)
	}
	if !strings.Contains(out, "empty=") {
		fmt.Fprintf(os.Stderr, "expected empty= in output, got %q\n", out)
		os.Exit(1)
	}

	// 5. Validation errors: ErrNilKey, ErrInvalidKey, and ErrUnsupportedKeyType
	buf.Reset()
	if err := enc.EncodeKeyval(nil, "value"); !errors.Is(err, logfmt.ErrNilKey) {
		fmt.Fprintf(os.Stderr, "expected ErrNilKey for nil key, got %v\n", err)
		os.Exit(1)
	}

	enc.Reset()
	if err := enc.EncodeKeyval("   ", "value"); !errors.Is(err, logfmt.ErrInvalidKey) {
		fmt.Fprintf(os.Stderr, "expected ErrInvalidKey for empty key, got %v\n", err)
		os.Exit(1)
	}

	enc.Reset()
	if err := enc.EncodeKeyval(unsupportedType{num: 42}, "value"); !errors.Is(err, logfmt.ErrUnsupportedKeyType) {
		fmt.Fprintf(os.Stderr, "expected ErrUnsupportedKeyType for unsupported struct key, got %v\n", err)
		os.Exit(1)
	}

	// 6. ErrUnsupportedValueType is returned for unsupported value types
	enc.Reset()
	if err := enc.EncodeKeyval("k", unsupportedType{num: 42}); !errors.Is(err, logfmt.ErrUnsupportedValueType) {
		fmt.Fprintf(os.Stderr, "expected ErrUnsupportedValueType for unsupported value, got %v\n", err)
		os.Exit(1)
	}

	// 7. fmt.Stringer is supported as valid key and value
	enc.Reset()
	buf.Reset()
	if err := enc.EncodeKeyval(customStringer{val: "custom_key"}, customStringer{val: "custom value"}); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeKeyval with customStringer failed: %v\n", err)
		os.Exit(1)
	}
	if err := enc.EndRecord(); err != nil {
		fmt.Fprintf(os.Stderr, "EndRecord failed: %v\n", err)
		os.Exit(1)
	}
	if buf.String() != "custom_key=\"custom value\"\n" {
		fmt.Fprintf(os.Stderr, "expected custom_key=\"custom value\", got %q\n", buf.String())
		os.Exit(1)
	}

	// 8. Reset clears error state on the encoder allowing subsequent writes
	buf.Reset()
	enc.Reset()
	if err := enc.EncodeKeyval("status", "healthy"); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeKeyval after Reset failed: %v\n", err)
		os.Exit(1)
	}
	if err := enc.EndRecord(); err != nil {
		fmt.Fprintf(os.Stderr, "EndRecord after Reset failed: %v\n", err)
		os.Exit(1)
	}
	if buf.String() != "status=healthy\n" {
		fmt.Fprintf(os.Stderr, "expected status=healthy, got %q\n", buf.String())
		os.Exit(1)
	}

	// 9. LogEncoder wrapper in sample package correctly formats records
	buf.Reset()
	logEnc := sample.NewLogEncoder(&buf)
	if err := logEnc.EncodeField("module", "auth"); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeField failed: %v\n", err)
		os.Exit(1)
	}
	if err := logEnc.EncodeField("action", "login"); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeField failed: %v\n", err)
		os.Exit(1)
	}
	if err := logEnc.EndLine(); err != nil {
		fmt.Fprintf(os.Stderr, "EndLine failed: %v\n", err)
		os.Exit(1)
	}
	if err := logEnc.EncodeEntry("event", "success", "user_id", 42); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeEntry failed: %v\n", err)
		os.Exit(1)
	}
	expectedLog := "module=auth action=login\nevent=success user_id=42\n"
	if buf.String() != expectedLog {
		fmt.Fprintf(os.Stderr, "expected %q, got %q\n", expectedLog, buf.String())
		os.Exit(1)
	}

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

Seeder de origem

anônimo