CodeSampleX

示例

github.com/go-chi/chi/v5 v5.3.1: middleware.Timeout requires cooperative ctx.Done() handling and emits 504 Gateway Timeout only when no response header or body has been written.

已验证示例 — golang github.com/go-chi/chi/v5 v5.3.1: middleware.Timeout requires cooperative ctx.Done() handling and emits 504 Gateway Timeout only when no…

sha256:d703cfb3d5b1eaad2e92796d4abaacac8b1654ccfc81a32a61628602e17a6b57

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

执行证据

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

证据依据
签名契约通过
验证回执
3
构建过它的签名密钥
2
声明的环境 go linux x64 go go go

验证运行环境

环境 契约 阶段 运行日期
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-17
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-18
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 FAIL compile:SKIPPED · contract:FAIL · load:SKIPPED · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-09-07

案例

HOW
目标
middleware.Timeout requires cooperative ctx.Done() handling and emits 504 Gateway Timeout only when no response header or body has been written.
包
符号
  • middleware.Timeout
环境
go
创建时间
2026-08-17T07:26:05Z

契约

  1. When a handler cooperatively returns upon ctx.Done() without writing to ResponseWriter, middleware.Timeout writes HTTP 504 StatusGatewayTimeout with an empty body.
  2. When a handler blocks synchronously without selecting on ctx.Done(), middleware.Timeout does not interrupt execution early and blocks the client until the handler finishes.
  3. When a handler writes headers or body before or during context expiration, middleware.Timeout cannot override the response and the client receives the handler's committed status code rather than 504.
  4. When a fast handler completes within the timeout, middleware.Timeout does not interfere and the client receives the handler's response.
  5. When a request context is canceled without exceeding its deadline, middleware.Timeout does not write HTTP 504.

文件

  • NOTES.md
  • csx.json
  • go.mod
  • go.sum
  • timeout_test.go

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Chi middleware.Timeout Behavior

search_known_solution returned hits in the same package for other middleware interactions (such as URLFormat/StripSlashes ordering and RealIP extraction in sample sha256:927db3ceea28b745375befa8e666fa49cd4bd8f3d81e6fecb501212db5ab541b), but no existing verified sample specifically exercising middleware.Timeout.

## Pinned Release
- Package: github.com/go-chi/chi/v5
- Release: v5.3.1

## Observed Behavior
In github.com/go-chi/chi/v5/middleware, Timeout(timeout time.Duration) attaches context.WithTimeout to the incoming HTTP request context and invokes next.ServeHTTP(w, r) synchronously on the same goroutine. In a deferred block, it verifies if ctx.Err() == context.DeadlineExceeded and calls w.WriteHeader(http.StatusGatewayTimeout).

Key consequences:
1. Cooperative Cancellation: Because middleware.Timeout executes synchronously without spawning a background handler goroutine or buffering output, the downstream handler must explicitly monitor <-r.Context().Done() and return. If a handler performs blocking I/O or sleep operations without checking context cancellation, the client remains blocked until the handler completes.
2. Prior Response Writes Suppress 504: If the handler commits a response by calling w.WriteHeader(...) or writing to w before context deadline expiration, the deferred w.WriteHeader(http.StatusGatewayTimeout) is ignored as a superfluous header write by the underlying HTTP server. The client receives the committed response (e.g. 200 OK) rather than 504 Gateway Timeout.
3. Empty Body on Gateway Timeout: When a handler cooperatively returns upon context deadline exceeded without writing to w, middleware.Timeout writes HTTP 504 with an empty body.
4. Client Cancellation Distinction: If the request context is canceled by the client without reaching deadline expiration (ctx.Err() == context.Canceled), middleware.Timeout does not emit 504 Gateway Timeout.

## Failure Mode
The naive expectation that middleware.Timeout will asynchronously interrupt slow handlers and guarantee a 504 Gateway Timeout fails silently with a green build path when handlers perform blocking un-cancellable operations or write response data before returning, yielding 200 OK after the full blocking duration.
csx.json
{"case":{"believed":"middleware.Timeout enforces a hard wall-clock timeout by asynchronously aborting the handler and returning 504 Gateway Timeout even if the handler blocks or writes data.","caseId":"case:sha256:ceafb12a0f3ffa6a94d79393f26af13ec3e3f03f298277f71ce35fd2a59c6db8","contract":["When a handler cooperatively returns upon ctx.Done() without writing to ResponseWriter, middleware.Timeout writes HTTP 504 StatusGatewayTimeout with an empty body.","When a handler blocks synchronously without selecting on ctx.Done(), middleware.Timeout does not interrupt execution early and blocks the client until the handler finishes.","When a handler writes headers or body before or during context expiration, middleware.Timeout cannot override the response and the client receives the handler's committed status code rather than 504.","When a fast handler completes within the timeout, middleware.Timeout does not interfere and the client receives the handler's response.","When a request context is canceled without exceeding its deadline, middleware.Timeout does not write HTTP 504."],"goal":"middleware.Timeout requires cooperative ctx.Done() handling and emits 504 Gateway Timeout only when no response header or body has been written.","kind":"HOW","packages":["pkg:golang/github.com/go-chi/chi/v5@5.3.1"],"schemaVersion":1,"symbols":["middleware.Timeout"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/go-chi/chi/v5@5.3.1"],"schemaVersion":1,"symbols":["middleware.Timeout"],"verifierAdapter":"golang@1"}
go.mod
module timeout_sample

go 1.23

require github.com/go-chi/chi/v5 v5.3.1
go.sum
github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8=
github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
timeout_test.go
package main

import (
	"context"
	"io"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
)

func TestTimeout(t *testing.T) {
	t.Run("CooperativeHandlerReturns504", func(t *testing.T) {
		router := chi.NewRouter()
		router.Use(middleware.Timeout(50 * time.Millisecond))
		router.Get("/coop", func(w http.ResponseWriter, r *http.Request) {
			select {
			case <-r.Context().Done():
				// Cooperatively return upon deadline without writing to w
				return
			case <-time.After(500 * time.Millisecond):
				w.WriteHeader(http.StatusOK)
				_, _ = w.Write([]byte("unreachable"))
			}
		})

		server := httptest.NewServer(router)
		defer server.Close()

		start := time.Now()
		resp, err := server.Client().Get(server.URL + "/coop")
		if err != nil {
			t.Fatal(err)
		}
		defer resp.Body.Close()
		body, _ := io.ReadAll(resp.Body)
		elapsed := time.Since(start)

		if got, want := resp.StatusCode, http.StatusGatewayTimeout; got != want {
			t.Fatalf("expected status %d, got %d", want, got)
		}
		if len(body) != 0 {
			t.Fatalf("expected empty response body for 504, got %q", string(body))
		}
		if elapsed > 250*time.Millisecond {
			t.Fatalf("expected cooperative exit around 50ms, took %v", elapsed)
		}
	})

	t.Run("NonCooperativeHandlerBlocksSynchronously", func(t *testing.T) {
		router := chi.NewRouter()
		router.Use(middleware.Timeout(50 * time.Millisecond))
		router.Get("/blocking", func(w http.ResponseWriter, r *http.Request) {
			// Simulates blocking un-cancellable work without checking ctx.Done()
			time.Sleep(200 * time.Millisecond)
		})

		server := httptest.NewServer(router)
		defer server.Close()

		start := time.Now()
		resp, err := server.Client().Get(server.URL + "/blocking")
		if err != nil {
			t.Fatal(err)
		}
		defer resp.Body.Close()
		elapsed := time.Since(start)

		if got, want := resp.StatusCode, http.StatusGatewayTimeout; got != want {
			t.Fatalf("expected status %d, got %d", want, got)
		}
		if elapsed < 180*time.Millisecond {
			t.Fatalf("expected request to block for full sleep duration (at least 180ms), took %v", elapsed)
		}
	})

	t.Run("CommittedWritesSuppress504Status", func(t *testing.T) {
		router := chi.NewRouter()
		router.Use(middleware.Timeout(50 * time.Millisecond))
		router.Get("/written", func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusOK)
			_, _ = w.Write([]byte("committed body"))
			<-r.Context().Done()
		})

		server := httptest.NewServer(router)
		defer server.Close()

		resp, err := server.Client().Get(server.URL + "/written")
		if err != nil {
			t.Fatal(err)
		}
		defer resp.Body.Close()
		body, _ := io.ReadAll(resp.Body)

		if got, want := resp.StatusCode, http.StatusOK; got != want {
			t.Fatalf("expected committed status %d, got %d", want, got)
		}
		if got, want := string(body), "committed body"; got != want {
			t.Fatalf("expected body %q, got %q", want, got)
		}
	})

	t.Run("FastHandlerCompletesWithinTimeout", func(t *testing.T) {
		router := chi.NewRouter()
		router.Use(middleware.Timeout(500 * time.Millisecond))
		router.Get("/fast", func(w http.ResponseWriter, r *http.Request) {
			w.WriteHeader(http.StatusAccepted)
			_, _ = w.Write([]byte("fast response"))
		})

		server := httptest.NewServer(router)
		defer server.Close()

		resp, err := server.Client().Get(server.URL + "/fast")
		if err != nil {
			t.Fatal(err)
		}
		defer resp.Body.Close()
		body, _ := io.ReadAll(resp.Body)

		if got, want := resp.StatusCode, http.StatusAccepted; got != want {
			t.Fatalf("expected status %d, got %d", want, got)
		}
		if got, want := string(body), "fast response"; got != want {
			t.Fatalf("expected body %q, got %q", want, got)
		}
	})

	t.Run("ContextCanceledWithoutDeadlineDoesNotEmit504", func(t *testing.T) {
		router := chi.NewRouter()
		router.Use(middleware.Timeout(10 * time.Second))
		router.Get("/cancel", func(w http.ResponseWriter, r *http.Request) {
			// Handler does not write anything and returns
		})

		ctx, cancel := context.WithCancel(context.Background())
		cancel()

		rec := httptest.NewRecorder()
		req := httptest.NewRequest("GET", "/cancel", nil).WithContext(ctx)

		router.ServeHTTP(rec, req)

		if rec.Code == http.StatusGatewayTimeout {
			t.Fatalf("expected non-504 status on client cancellation, got 504")
		}
	})
}

原始种子者

csx-seed