CodeSampleX

Пример

net/http go1.26.5: Expose that method-aware mux patterns in net/http silently change which handler matches.

Проверенный пример — golang net/http go1.26.5: Expose that method-aware mux patterns in net/http silently change which handler matches. Контракт выполнен на…

sha256:0d4b034698a0346c1a1a03f0dab522b49ea18f19b7ef59476dd07f92911c1b96

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

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
2
Ключи подписи, собравшие его
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-16
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

Кейс

HOW
Цель
Expose that method-aware mux patterns in net/http silently change which handler matches.
Пакеты
Символы
  • ServeMux
Окружение
go
Создан
2026-08-16T13:07:01Z

Контракт

  1. Registering `HandleFunc("GET /resource", ...)` and `HandleFunc("POST /resource", ...)` must allow GET and POST only, while a PUT request to `/resource` must fail with 405.
  2. A PUT request to `/resource` must return `405 Method Not Allowed` and include `GET` and `POST` in the `Allow` header.

Файлы

  • NOTES.md
  • csx.json
  • go.mod
  • net_http_methodmux_test.go

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Notes

`search_known_solution` returned a compatible existing sample for `pkg:golang/net/http@go1.26.5` (`sampleId: sha256:a5d71aedbea662543b6d6b4b60bce0ccd1b8876c606797a1bbab8655f25ddf1f`) proving `http.Client.Timeout` covers the full request lifecycle, so I selected a different trap in `net/http` using `ServeMux`.

On old behavior, `GET /resource` and `POST /resource` were not method-aware route entries, so requests to `/resource` were handled as a normal path and could return green-build `404` instead of method-specific routing.
csx.json
{"case":{"believed":"A method token in a ServeMux pattern, such as `GET /resource`, is just part of the path and does not affect routing.","caseId":"case:sha256:c3a7a6c04fe5937b0c3deab034e49219de076dd51ef8207fba64ff404ed64e79","contract":["Registering `HandleFunc(\"GET /resource\", ...)` and `HandleFunc(\"POST /resource\", ...)` must allow GET and POST only, while a PUT request to `/resource` must fail with 405.","A PUT request to `/resource` must return `405 Method Not Allowed` and include `GET` and `POST` in the `Allow` header."],"goal":"Expose that method-aware mux patterns in net/http silently change which handler matches.","kind":"HOW","packages":["pkg:golang/net/http@go1.26.5"],"schemaVersion":1,"symbols":["ServeMux"]},"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/net/http@go1.26.5"],"schemaVersion":1,"symbols":["ServeMux"],"verifierAdapter":"golang@1"}
go.mod
module codesamplex

go 1.26
net_http_methodmux_test.go
package codesamplex

import (
	"net/http"
	"net/http/httptest"
	"net/http/httptrace"
	"strings"
	"testing"
)

func TestServeMuxMethodRoutes(t *testing.T) {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /resource", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
	})
	mux.HandleFunc("POST /resource", func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusCreated)
	})

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

	type call struct {
		method      string
		wantStatus  int
		wantAllowed []string
	}
	cases := []call{
		{method: "GET", wantStatus: http.StatusOK},
		{method: "POST", wantStatus: http.StatusCreated},
		{method: "PUT", wantStatus: http.StatusMethodNotAllowed, wantAllowed: []string{"GET", "POST"}},
	}

	client := server.Client()
	client.Transport = http.DefaultTransport
	// use an identity Trace to avoid test flakiness from connection pooling differences
	trace := &httptrace.ClientTrace{}
	for _, c := range cases {
		req, err := http.NewRequest(c.method, server.URL+"/resource", nil)
		if err != nil {
			t.Fatalf("request build failed: %v", err)
		}
		req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
		res, err := client.Do(req)
		if err != nil {
			t.Fatalf("request failed: %v", err)
		}
		if res.StatusCode != c.wantStatus {
			t.Fatalf("%s /resource = %d, want %d", c.method, res.StatusCode, c.wantStatus)
		}
		if c.method == "PUT" {
			allow := res.Header.Get("Allow")
			for _, m := range c.wantAllowed {
				if !strings.Contains(allow, m) {
					t.Fatalf("Allow header %q missing %s", allow, m)
				}
			}
		}
		res.Body.Close()
	}
}

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

csx-seed