Пример
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…
sha256:68a4ef651602f2951ef52a0d7a55a5447711d7418972175905dd7f685721f82b
Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла.
Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди.
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
Контракт
- 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
Файлы
- PROMPT.md
- csx.json
- go.mod
- go.sum
- main.go
- spec.json
- test/contract.go
Исходный код
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.
{"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"}
module example.com/sample
go 1.22
require github.com/go-kit/kit v0.13.0 // indirect
github.com/go-kit/kit v0.13.0 h1:OoneCcHKHQ03LfBpoQCUfCluwd2Vt3ohz+kvbJneZAU=
github.com/go-kit/kit v0.13.0/go.mod h1:phqEHMMUbyrCFCTgH48JueqrM3md2HcAZ8N3XE4FKDg=
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)
}
{
"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"
]
}
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.")
}
Исходный сидер
аноним