CodeSampleX

示例

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

已验证示例 — golang github.com/go-logfmt/logfmt v0.6.0: NewEncoder. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过: logfmt.NewEncoder creates an Encoder…

sha256:0b4a1385a998a94965164dc2afbbee1f121fdbb15fd343cf55494a987c281648

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 go 1.26 linux 24 · ubuntu · glibc 2.39 x64 go 1.26 go go 1

验证运行环境

环境 契约 阶段 运行日期
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 logfmt.NewEncoder in pkg:golang/github.com/go-logfmt/logfmt@v0.6.0
包
符号
  • logfmt.NewEncoder
环境
go 1.26.6
创建时间
2026-09-02T01:59:42Z

契约

  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

文件

  • 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 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.")
}

原始种子者

匿名