CodeSampleX

サンプル

github.com/go-kit/kit v0.13.0: endpoint middleware chaining with go-kit

検証済みサンプル — golang github.com/go-kit/kit v0.13.0: endpoint middleware chaining with go-kit. go 1.26 · linux alpine/x64 · docker で contract を実行し、成功しました.

sha256:68a4ef651602f2951ef52a0d7a55a5447711d7418972175905dd7f685721f82b

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 go

検証実行環境

環境 コントラクト ステージ 実行日
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-23

ケース

HOW
ゴール
endpoint middleware chaining with go-kit
パッケージ
シンボル
  • endpoint.Chain
  • endpoint.Endpoint
  • endpoint.Middleware
作成日
2026-08-23T17:32:50Z

コントラクト

  1. endpoint.Chain wraps an Endpoint with multiple Middlewares in outer-to-inner execution order
  2. endpoint.Chain propagates context values, request arguments, and response values through the chain
  3. endpoint.Chain short-circuits execution when an outer Middleware intercepts without invoking next

ファイル

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.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: endpoint middleware chaining with go-kit
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/go-kit/kit@v0.13.0
Demonstrate these symbols/APIs:
  - endpoint.Chain
  - endpoint.Endpoint
  - endpoint.Middleware

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:11b88b2af24e8c8fe73cc8ff7e5d99c936a97cbd017c7fcb98692a6e30661e05","contract":["endpoint.Chain wraps an Endpoint with multiple Middlewares in outer-to-inner execution order","endpoint.Chain propagates context values, request arguments, and response values through the chain","endpoint.Chain short-circuits execution when an outer Middleware intercepts without invoking next"],"goal":"endpoint middleware chaining with go-kit","kind":"HOW","packages":["pkg:golang/github.com/go-kit/kit@v0.13.0"],"schemaVersion":1,"symbols":["endpoint.Chain","endpoint.Endpoint","endpoint.Middleware"]},"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-kit/kit@v0.13.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/go-kit/kit@v0.13.0","symbols":["endpoint.Chain","endpoint.Endpoint","endpoint.Middleware"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22

require github.com/go-kit/kit v0.13.0 // indirect
go.sum
github.com/go-kit/kit v0.13.0 h1:OoneCcHKHQ03LfBpoQCUfCluwd2Vt3ohz+kvbJneZAU=
github.com/go-kit/kit v0.13.0/go.mod h1:phqEHMMUbyrCFCTgH48JueqrM3md2HcAZ8N3XE4FKDg=
main.go
package main

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/go-kit/kit/endpoint"
)

type UppercaseRequest struct {
	Text string
}

type UppercaseResponse struct {
	Text string
	Err  error
}

func makeUppercaseEndpoint() endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		req := request.(UppercaseRequest)
		return UppercaseResponse{
			Text: strings.ToUpper(req.Text),
		}, nil
	}
}

func loggingMiddleware() endpoint.Middleware {
	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (interface{}, error) {
			req := request.(UppercaseRequest)
			fmt.Printf("[logging] processing request: %q\n", req.Text)
			resp, err := next(ctx, request)
			fmt.Printf("[logging] finished request: %q\n", req.Text)
			return resp, err
		}
	}
}

func timingMiddleware() endpoint.Middleware {
	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (interface{}, error) {
			start := time.Now()
			resp, err := next(ctx, request)
			fmt.Printf("[timing] execution took: %s\n", time.Since(start).Round(time.Microsecond))
			return resp, err
		}
	}
}

func main() {
	var ep endpoint.Endpoint
	ep = makeUppercaseEndpoint()

	// Chain middlewares: logging is outermost, timing is inner
	chainedEndpoint := endpoint.Chain(
		loggingMiddleware(),
		timingMiddleware(),
	)(ep)

	ctx := context.Background()
	resp, err := chainedEndpoint(ctx, UppercaseRequest{Text: "hello world"})
	if err != nil {
		fmt.Printf("endpoint error: %v\n", err)
		return
	}

	result := resp.(UppercaseResponse)
	fmt.Printf("Result: %s\n", result.Text)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "endpoint middleware chaining with go-kit",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-kit/kit@v0.13.0"
  ],
  "symbols": [
    "endpoint.Chain",
    "endpoint.Endpoint",
    "endpoint.Middleware"
  ]
}
test/contract.go
package main

import (
	"context"
	"errors"
	"fmt"
	"os"
	"reflect"

	"github.com/go-kit/kit/endpoint"
)

type contextKey string

const testKey contextKey = "test-key"

func main() {
	// Assertion 1: endpoint.Chain wraps an Endpoint with multiple Middlewares in outer-to-inner execution order
	var executionOrder []string

	recordMiddleware := func(name string) endpoint.Middleware {
		return func(next endpoint.Endpoint) endpoint.Endpoint {
			return func(ctx context.Context, req interface{}) (interface{}, error) {
				executionOrder = append(executionOrder, name+"_before")
				resp, err := next(ctx, req)
				executionOrder = append(executionOrder, name+"_after")
				return resp, err
			}
		}
	}

	baseEndpoint := func(ctx context.Context, req interface{}) (interface{}, error) {
		executionOrder = append(executionOrder, "endpoint")
		return "ok", nil
	}

	chained := endpoint.Chain(
		recordMiddleware("m1"),
		recordMiddleware("m2"),
		recordMiddleware("m3"),
	)(baseEndpoint)

	_, err := chained(context.Background(), "test")
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: unexpected error: %v\n", err)
		os.Exit(1)
	}

	expectedOrder := []string{
		"m1_before",
		"m2_before",
		"m3_before",
		"endpoint",
		"m3_after",
		"m2_after",
		"m1_after",
	}

	if !reflect.DeepEqual(executionOrder, expectedOrder) {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: expected order %v, got %v\n", expectedOrder, executionOrder)
		os.Exit(1)
	}

	// Assertion 2: endpoint.Chain propagates context values, request arguments, and response values through the chain
	contextMiddleware := func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, req interface{}) (interface{}, error) {
			newCtx := context.WithValue(ctx, testKey, "injected-value")
			inputStr := req.(string) + "-annotated"
			resp, err := next(newCtx, inputStr)
			if err != nil {
				return nil, err
			}
			return resp.(string) + "-wrapped", nil
		}
	}

	echoEndpoint := func(ctx context.Context, req interface{}) (interface{}, error) {
		ctxVal, ok := ctx.Value(testKey).(string)
		if !ok || ctxVal != "injected-value" {
			return nil, fmt.Errorf("context value mismatch: %v", ctxVal)
		}
		return req.(string) + "-echo", nil
	}

	chainedContext := endpoint.Chain(contextMiddleware)(echoEndpoint)
	resp2, err := chainedContext(context.Background(), "hello")
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: unexpected error: %v\n", err)
		os.Exit(1)
	}

	expectedResp := "hello-annotated-echo-wrapped"
	if resp2 != expectedResp {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: expected %q, got %q\n", expectedResp, resp2)
		os.Exit(1)
	}

	// Assertion 3: endpoint.Chain short-circuits execution when an outer Middleware intercepts without invoking next
	var innerCalled bool
	shortCircuitMiddleware := func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, req interface{}) (interface{}, error) {
			return nil, errors.New("intercepted")
		}
	}

	innerMiddleware := func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, req interface{}) (interface{}, error) {
			innerCalled = true
			return next(ctx, req)
		}
	}

	interceptedChained := endpoint.Chain(
		shortCircuitMiddleware,
		innerMiddleware,
	)(baseEndpoint)

	_, err = interceptedChained(context.Background(), "test")
	if err == nil || err.Error() != "intercepted" {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: expected 'intercepted' error, got %v\n", err)
		os.Exit(1)
	}

	if innerCalled {
		fmt.Fprintf(os.Stderr, "assertion 3 failed: inner middleware was called despite short circuit\n")
		os.Exit(1)
	}

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

オリジンシーダー

匿名