CodeSampleX

Пример

golang.org/x/net v0.29.0: websocket.Conn

Проверенный пример — golang golang.org/x/net v0.29.0: websocket.Conn. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден.

sha256:b9f1b6b84609239dd40e3256b7bcffdbef91816b93fb142a258393fa7f619c89

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-04

Кейс

HOW
Цель
verify golang.org/x/net/websocket.Conn in pkg:golang/golang.org/x/net@v0.29.0
Пакеты
Символы
  • golang.org/x/net/websocket.Conn
Создан
2026-09-04T02:48:26Z

Контракт

  1. websocket.Conn represents an established WebSocket connection implementing io.ReadWriteCloser
  2. websocket.Conn.IsServerConn returns true on the server side and false on the client side
  3. websocket.Conn.IsClientConn returns true on the client side and false on the server side
  4. websocket.Conn.Config returns the negotiated WebSocket configuration
  5. websocket.Conn.Request returns the underlying HTTP upgrade request on the server connection
  6. websocket.Conn.LocalAddr and RemoteAddr return valid network addresses
  7. websocket.Message codec sends and receives text frames across websocket.Conn
  8. websocket.Message codec sends and receives binary frames across websocket.Conn
  9. websocket.Conn.SetDeadline sets connection deadlines without error
  10. websocket.Conn.Close terminates the connection causing subsequent operations to return an error

Файлы

  • 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: verify golang.org/x/net/websocket.Conn in pkg:golang/golang.org/x/net@v0.29.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/net@v0.29.0
Demonstrate these symbols/APIs:
  - golang.org/x/net/websocket.Conn

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:d95e6984649b4ecba1beb0bc2b30f6931e870466fcc20db3bcfb329038622133","contract":["websocket.Conn represents an established WebSocket connection implementing io.ReadWriteCloser","websocket.Conn.IsServerConn returns true on the server side and false on the client side","websocket.Conn.IsClientConn returns true on the client side and false on the server side","websocket.Conn.Config returns the negotiated WebSocket configuration","websocket.Conn.Request returns the underlying HTTP upgrade request on the server connection","websocket.Conn.LocalAddr and RemoteAddr return valid network addresses","websocket.Message codec sends and receives text frames across websocket.Conn","websocket.Message codec sends and receives binary frames across websocket.Conn","websocket.Conn.SetDeadline sets connection deadlines without error","websocket.Conn.Close terminates the connection causing subsequent operations to return an error"],"goal":"verify golang.org/x/net/websocket.Conn in pkg:golang/golang.org/x/net@v0.29.0","kind":"HOW","packages":["pkg:golang/golang.org/x/net@v0.29.0"],"schemaVersion":1,"symbols":["golang.org/x/net/websocket.Conn"]},"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/golang.org/x/net@v0.29.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/net@v0.29.0","symbols":["golang.org/x/net/websocket.Conn"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.23.0

require golang.org/x/net v0.29.0
go.sum
golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo=
golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0=
main.go
package main

import (
	"fmt"
	"net/http/httptest"
	"strings"

	"golang.org/x/net/websocket"
)

func main() {
	// Start an in-memory test HTTP server with a websocket.Handler
	server := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
		defer ws.Close()

		var msg string
		if err := websocket.Message.Receive(ws, &msg); err != nil {
			fmt.Printf("server receive error: %v\n", err)
			return
		}
		fmt.Printf("Server received: %s\n", msg)

		reply := "Echo: " + msg
		if err := websocket.Message.Send(ws, reply); err != nil {
			fmt.Printf("server send error: %v\n", err)
			return
		}
	}))
	defer server.Close()

	// Convert http URL to ws URL
	wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws"
	origin := "http://localhost/"

	// Dial the WebSocket server to get a client websocket.Conn
	ws, err := websocket.Dial(wsURL, "", origin)
	if err != nil {
		fmt.Printf("websocket dial failed: %v\n", err)
		return
	}
	defer ws.Close()

	fmt.Printf("Connected! IsClientConn: %v, IsServerConn: %v\n", ws.IsClientConn(), ws.IsServerConn())

	// Send a message over websocket.Conn
	text := "Hello, WebSocket!"
	if err := websocket.Message.Send(ws, text); err != nil {
		fmt.Printf("client send error: %v\n", err)
		return
	}

	// Receive echo reply over websocket.Conn
	var reply string
	if err := websocket.Message.Receive(ws, &reply); err != nil {
		fmt.Printf("client receive error: %v\n", err)
		return
	}
	fmt.Printf("Client received reply: %s\n", reply)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/net/websocket.Conn in pkg:golang/golang.org/x/net@v0.29.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/net@v0.29.0"
  ],
  "symbols": [
    "golang.org/x/net/websocket.Conn"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http/httptest"
	"os"
	"strings"
	"sync"
	"time"

	"golang.org/x/net/websocket"
)

func main() {
	// 1. websocket.Conn represents an established WebSocket connection implementing io.ReadWriteCloser
	{
		var rwc io.ReadWriteCloser = (*websocket.Conn)(nil)
		_ = rwc
	}

	var serverConn *websocket.Conn
	var serverWg sync.WaitGroup
	serverWg.Add(1)

	textReceivedByServer := make(chan string, 1)
	binaryReceivedByServer := make(chan []byte, 1)

	server := httptest.NewServer(websocket.Handler(func(ws *websocket.Conn) {
		serverConn = ws
		serverWg.Done()

		// Receive text
		var txt string
		if err := websocket.Message.Receive(ws, &txt); err == nil {
			textReceivedByServer <- txt
		}

		// Echo text back
		_ = websocket.Message.Send(ws, "reply: "+txt)

		// Receive binary
		var bin []byte
		if err := websocket.Message.Receive(ws, &bin); err == nil {
			binaryReceivedByServer <- bin
		}

		// Echo binary back
		_ = websocket.Message.Send(ws, append([]byte("echo:"), bin...))

		// Wait until client closes or disconnects
		buf := make([]byte, 10)
		for {
			_, err := ws.Read(buf)
			if err != nil {
				break
			}
		}
	}))
	defer server.Close()

	wsURL := "ws" + strings.TrimPrefix(server.URL, "http") + "/ws"
	origin := "http://localhost/"

	clientConn, err := websocket.Dial(wsURL, "", origin)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Contract failed: websocket.Dial error: %v\n", err)
		os.Exit(1)
	}
	serverWg.Wait()

	// 2. websocket.Conn.IsServerConn returns true on the server side and false on the client side
	{
		if !serverConn.IsServerConn() {
			fmt.Fprintf(os.Stderr, "Contract 2 failed: expected serverConn.IsServerConn() to be true\n")
			os.Exit(1)
		}
		if clientConn.IsServerConn() {
			fmt.Fprintf(os.Stderr, "Contract 2 failed: expected clientConn.IsServerConn() to be false\n")
			os.Exit(1)
		}
	}

	// 3. websocket.Conn.IsClientConn returns true on the client side and false on the server side
	{
		if !clientConn.IsClientConn() {
			fmt.Fprintf(os.Stderr, "Contract 3 failed: expected clientConn.IsClientConn() to be true\n")
			os.Exit(1)
		}
		if serverConn.IsClientConn() {
			fmt.Fprintf(os.Stderr, "Contract 3 failed: expected serverConn.IsClientConn() to be false\n")
			os.Exit(1)
		}
	}

	// 4. websocket.Conn.Config returns the negotiated WebSocket configuration
	{
		cfg := clientConn.Config()
		if cfg == nil {
			fmt.Fprintf(os.Stderr, "Contract 4 failed: clientConn.Config() is nil\n")
			os.Exit(1)
		}
		if cfg.Origin == nil || cfg.Origin.String() != origin {
			fmt.Fprintf(os.Stderr, "Contract 4 failed: origin mismatch: got %v, want %s\n", cfg.Origin, origin)
			os.Exit(1)
		}
		if cfg.Version != websocket.ProtocolVersionHybi13 {
			fmt.Fprintf(os.Stderr, "Contract 4 failed: expected Hybi13 protocol version, got %d\n", cfg.Version)
			os.Exit(1)
		}
	}

	// 5. websocket.Conn.Request returns the underlying HTTP upgrade request on the server connection
	{
		req := serverConn.Request()
		if req == nil {
			fmt.Fprintf(os.Stderr, "Contract 5 failed: serverConn.Request() is nil\n")
			os.Exit(1)
		}
		if req.Method != "GET" {
			fmt.Fprintf(os.Stderr, "Contract 5 failed: expected GET method, got %s\n", req.Method)
			os.Exit(1)
		}
		if !strings.EqualFold(req.Header.Get("Upgrade"), "websocket") {
			fmt.Fprintf(os.Stderr, "Contract 5 failed: missing Upgrade header in server request\n")
			os.Exit(1)
		}
		if clientConn.Request() != nil {
			fmt.Fprintf(os.Stderr, "Contract 5 failed: clientConn.Request() should be nil\n")
			os.Exit(1)
		}
	}

	// 6. websocket.Conn.LocalAddr and RemoteAddr return valid network addresses
	{
		if clientConn.LocalAddr() == nil || clientConn.LocalAddr().String() == "" {
			fmt.Fprintf(os.Stderr, "Contract 6 failed: clientConn.LocalAddr() is invalid\n")
			os.Exit(1)
		}
		if clientConn.RemoteAddr() == nil || clientConn.RemoteAddr().String() == "" {
			fmt.Fprintf(os.Stderr, "Contract 6 failed: clientConn.RemoteAddr() is invalid\n")
			os.Exit(1)
		}
		if serverConn.LocalAddr() == nil || serverConn.RemoteAddr() == nil {
			fmt.Fprintf(os.Stderr, "Contract 6 failed: server addresses are invalid\n")
			os.Exit(1)
		}
	}

	// 7. websocket.Message codec sends and receives text frames across websocket.Conn
	{
		sentMsg := "test-message-12345"
		if err := websocket.Message.Send(clientConn, sentMsg); err != nil {
			fmt.Fprintf(os.Stderr, "Contract 7 failed: Send text error: %v\n", err)
			os.Exit(1)
		}
		recvByServer := <-textReceivedByServer
		if recvByServer != sentMsg {
			fmt.Fprintf(os.Stderr, "Contract 7 failed: text mismatch: got %q, want %q\n", recvByServer, sentMsg)
			os.Exit(1)
		}
		var echoReply string
		if err := websocket.Message.Receive(clientConn, &echoReply); err != nil {
			fmt.Fprintf(os.Stderr, "Contract 7 failed: Receive text reply error: %v\n", err)
			os.Exit(1)
		}
		expectedReply := "reply: " + sentMsg
		if echoReply != expectedReply {
			fmt.Fprintf(os.Stderr, "Contract 7 failed: reply mismatch: got %q, want %q\n", echoReply, expectedReply)
			os.Exit(1)
		}
	}

	// 8. websocket.Message codec sends and receives binary frames across websocket.Conn
	{
		sentBinary := []byte{0xDE, 0xAD, 0xBE, 0xEF}
		if err := websocket.Message.Send(clientConn, sentBinary); err != nil {
			fmt.Fprintf(os.Stderr, "Contract 8 failed: Send binary error: %v\n", err)
			os.Exit(1)
		}
		recvBinByServer := <-binaryReceivedByServer
		if !bytes.Equal(recvBinByServer, sentBinary) {
			fmt.Fprintf(os.Stderr, "Contract 8 failed: binary payload mismatch\n")
			os.Exit(1)
		}
		var echoBinReply []byte
		if err := websocket.Message.Receive(clientConn, &echoBinReply); err != nil {
			fmt.Fprintf(os.Stderr, "Contract 8 failed: Receive binary reply error: %v\n", err)
			os.Exit(1)
		}
		expectedBin := append([]byte("echo:"), sentBinary...)
		if !bytes.Equal(echoBinReply, expectedBin) {
			fmt.Fprintf(os.Stderr, "Contract 8 failed: binary reply mismatch: got %v, want %v\n", echoBinReply, expectedBin)
			os.Exit(1)
		}
	}

	// 9. websocket.Conn.SetDeadline sets connection deadlines without error
	{
		if err := clientConn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
			fmt.Fprintf(os.Stderr, "Contract 9 failed: SetDeadline error: %v\n", err)
			os.Exit(1)
		}
		if err := clientConn.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
			fmt.Fprintf(os.Stderr, "Contract 9 failed: SetReadDeadline error: %v\n", err)
			os.Exit(1)
		}
		if err := clientConn.SetWriteDeadline(time.Now().Add(5 * time.Second)); err != nil {
			fmt.Fprintf(os.Stderr, "Contract 9 failed: SetWriteDeadline error: %v\n", err)
			os.Exit(1)
		}
	}

	// 10. websocket.Conn.Close terminates the connection causing subsequent operations to return an error
	{
		if err := clientConn.Close(); err != nil {
			fmt.Fprintf(os.Stderr, "Contract 10 failed: Close error: %v\n", err)
			os.Exit(1)
		}
		var dummy string
		err := websocket.Message.Receive(clientConn, &dummy)
		if err == nil {
			fmt.Fprintf(os.Stderr, "Contract 10 failed: expected error reading from closed connection, got nil\n")
			os.Exit(1)
		}
	}

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

Исходный сидер

аноним