From 2e4d4f38962a6f15ae496d59b294f307eef95429 Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Mon, 22 Jun 2026 19:00:06 +0800 Subject: [PATCH 01/27] chore(deps): bump github.com/quic-go/quic-go to v0.60.0 (#4713) - Upgrade quic-go from v0.59.0 to v0.60.0 --- go.mod | 2 +- go.sum | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index df181253..705034ee 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/mattn/go-isatty v0.0.20 github.com/modern-go/reflect2 v1.0.2 github.com/pelletier/go-toml/v2 v2.2.4 - github.com/quic-go/quic-go v0.59.0 + github.com/quic-go/quic-go v0.60.0 github.com/stretchr/testify v1.11.1 github.com/ugorji/go/codec v1.3.1 go.mongodb.org/mongo-driver/v2 v2.5.0 diff --git a/go.sum b/go.sum index f7f9e27b..c38e6eae 100644 --- a/go.sum +++ b/go.sum @@ -50,10 +50,12 @@ github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0 github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4TzM7MFjy0= +github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= -github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= -github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +github.com/quic-go/quic-go v0.60.0 h1:xcQioE8OM66UQLeUMHltK1CCcOu3JbVB4JAQdDQSB+0= +github.com/quic-go/quic-go v0.60.0/go.mod h1:wpKpjmPpftl30sL6pFh7REVpjbcCVy4zt2vDyK1TuJk= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= From 293ad7edebb3ae30369288bd6416ca0d78474727 Mon Sep 17 00:00:00 2001 From: Amirhf Date: Mon, 22 Jun 2026 14:39:26 +0330 Subject: [PATCH 02/27] fix(context): Copy() copies Errors and Accepted fields (#4695) * Previously, Copy() only copied Keys and Params, leaving Errors and Accepted as nil even when set on the original context. Goroutines receiving a copied context could not observe errors attached before the copy, and content-negotiation state set by middleware was silently lost. * Replace assert.Equal(t, len(c.Errors), len(cp.Errors)) with assert.Len(t, cp.Errors, 2) to satisfy the testifylint linter rule --------- Co-authored-by: Bo-Yi Wu --- context.go | 10 ++++++++++ context_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/context.go b/context.go index a2e28e5b..640e20b2 100644 --- a/context.go +++ b/context.go @@ -141,6 +141,16 @@ func (c *Context) Copy() *Context { cp.Params = make([]Param, len(cParams)) copy(cp.Params, cParams) + if c.Errors != nil { + cp.Errors = make(errorMsgs, len(c.Errors)) + copy(cp.Errors, c.Errors) + } + + if c.Accepted != nil { + cp.Accepted = make([]string, len(c.Accepted)) + copy(cp.Accepted, c.Accepted) + } + return &cp } diff --git a/context_test.go b/context_test.go index 364a92ae..2dfdd392 100644 --- a/context_test.go +++ b/context_test.go @@ -689,6 +689,50 @@ func TestContextCopy(t *testing.T) { assert.Equal(t, cp.fullPath, c.fullPath) } +func TestContextCopyCopiesErrors(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + _ = c.Error(errors.New("first error")) + _ = c.Error(errors.New("second error")) + + cp := c.Copy() + + // copied context has the same errors + assert.Len(t, cp.Errors, 2) + assert.Equal(t, c.Errors[0].Error(), cp.Errors[0].Error()) + assert.Equal(t, c.Errors[1].Error(), cp.Errors[1].Error()) + + // mutations on the copy do not affect the original + _ = cp.Error(errors.New("third error")) + assert.Len(t, c.Errors, 2) + assert.Len(t, cp.Errors, 3) +} + +func TestContextCopyCopiesAccepted(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + c.SetAccepted("application/json", "text/html") + + cp := c.Copy() + + assert.Equal(t, c.Accepted, cp.Accepted) + + // mutations on the copy do not affect the original + cp.SetAccepted("text/plain") + assert.Equal(t, []string{"application/json", "text/html"}, c.Accepted) + assert.Equal(t, []string{"text/plain"}, cp.Accepted) +} + +func TestContextCopyNilErrorsAndAccepted(t *testing.T) { + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodGet, "/", nil) + + cp := c.Copy() + + assert.Nil(t, cp.Errors) + assert.Nil(t, cp.Accepted) +} + func TestContextHandlerName(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest} From 4a3eb31fb15b2a2d78b4bdbe0c31a2c564b1977a Mon Sep 17 00:00:00 2001 From: DadaVinqi Date: Mon, 22 Jun 2026 20:56:28 +0800 Subject: [PATCH 03/27] fix(recovery): record recovered panics in c.Errors (#4698) * fix: record recovered panic errors * chore(deps): bump quic-go to v0.59.1 * refactor(recovery): simplify panic error recording - Collapse the if/else into a single c.Error call in defaultHandleRecovery - Assert the recorded panic error is ErrorTypePrivate in the test Co-Authored-By: Claude Opus 4.8 (1M context) --------- Co-authored-by: m0_66095053 <2876430886@qq.com> Co-authored-by: Bo-Yi Wu Co-authored-by: Claude Opus 4.8 (1M context) --- recovery.go | 7 ++++++- recovery_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/recovery.go b/recovery.go index bbf1d565..2124fe5f 100644 --- a/recovery.go +++ b/recovery.go @@ -106,7 +106,12 @@ func secureRequestDump(r *http.Request) string { return strings.Join(lines, "\r\n") } -func defaultHandleRecovery(c *Context, _ any) { +func defaultHandleRecovery(c *Context, err any) { + e, ok := err.(error) + if !ok { + e = fmt.Errorf("%v", err) + } + c.Error(e) //nolint: errcheck c.AbortWithStatus(http.StatusInternalServerError) } diff --git a/recovery_test.go b/recovery_test.go index 028c4ad6..e5211790 100644 --- a/recovery_test.go +++ b/recovery_test.go @@ -5,6 +5,7 @@ package gin import ( + "errors" "net" "net/http" "os" @@ -152,6 +153,49 @@ func TestPanicWithAbortHandler(t *testing.T) { assert.NotContains(t, out, "panic recovered") } +func TestPanicInHandlerRecordsError(t *testing.T) { + tests := []struct { + name string + recoveredErr any + expectedErr string + }{ + { + name: "string panic", + recoveredErr: "Oops, Houston, we have a problem", + expectedErr: "Oops, Houston, we have a problem", + }, + { + name: "error panic", + recoveredErr: errors.New("recovered error"), + expectedErr: "recovered error", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + router := New() + + var recoveredErrors errorMsgs + router.Use(func(c *Context) { + c.Next() + recoveredErrors = c.Errors + }) + router.Use(RecoveryWithWriter(nil)) + router.GET("/recovery", func(_ *Context) { + panic(tt.recoveredErr) + }) + + w := PerformRequest(router, http.MethodGet, "/recovery") + + assert.Equal(t, http.StatusInternalServerError, w.Code) + if assert.Len(t, recoveredErrors, 1) { + assert.EqualError(t, recoveredErrors[0], tt.expectedErr) + assert.Equal(t, ErrorTypePrivate, recoveredErrors[0].Type) + } + }) + } +} + func TestCustomRecoveryWithWriter(t *testing.T) { errBuffer := new(strings.Builder) buffer := new(strings.Builder) From 074b669a95fd834701359acc55371e6b377618f6 Mon Sep 17 00:00:00 2001 From: MuaazTasawar Date: Mon, 22 Jun 2026 18:18:24 +0500 Subject: [PATCH 04/27] test(response_writer): add tests for Flush() with and without http.Flusher (#4699) * test(response_writer): add tests for Flush() with and without http.Flusher * test(response_writer): drop stray comment and clarify Flush regression note - Remove orphaned doc comment left at the end of the file - Reword the issue #4460 reference to reflect the no-panic guard --------- Co-authored-by: Bo-Yi Wu --- response_writer_test.go | 31 +++++++++++++++++++++++++++---- 1 file changed, 27 insertions(+), 4 deletions(-) diff --git a/response_writer_test.go b/response_writer_test.go index 83d3fc8b..03417375 100644 --- a/response_writer_test.go +++ b/response_writer_test.go @@ -15,10 +15,33 @@ import ( "github.com/stretchr/testify/require" ) -// TODO -// func (w *responseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { -// func (w *responseWriter) CloseNotify() <-chan bool { -// func (w *responseWriter) Flush() { +// TestResponseWriterFlushWithFlusher verifies Flush() calls the underlying Flusher. +func TestResponseWriterFlushWithFlusher(t *testing.T) { + testWriter := httptest.NewRecorder() + writer := &responseWriter{ResponseWriter: testWriter} + writer.Flush() + assert.True(t, testWriter.Flushed) +} + +// TestResponseWriterFlushWithNonFlusher verifies Flush() is a no-op +// when the underlying ResponseWriter does not implement http.Flusher. +// Guards against the panic reported in https://github.com/gin-gonic/gin/issues/4460 +func TestResponseWriterFlushWithNonFlusher(t *testing.T) { + nonFlusher := &nonFlusherWriter{header: http.Header{}} + writer := &responseWriter{ResponseWriter: nonFlusher} + require.NotPanics(t, func() { + writer.Flush() + }) +} + +// nonFlusherWriter is a minimal http.ResponseWriter that does NOT implement http.Flusher. +type nonFlusherWriter struct { + header http.Header +} + +func (w *nonFlusherWriter) Header() http.Header { return w.header } +func (w *nonFlusherWriter) Write(b []byte) (int, error) { return len(b), nil } +func (w *nonFlusherWriter) WriteHeader(code int) {} var ( _ ResponseWriter = &responseWriter{} From da1e108614ecbbadfa5736b1b297b16121d23b9b Mon Sep 17 00:00:00 2001 From: "Pierre F." Date: Mon, 22 Jun 2026 16:43:44 +0200 Subject: [PATCH 05/27] test(context): use t.TempDir() for SaveUploadedFile permission test on WSL (#4709) * fix: change file creation to use c.Temp instead to work on wsl * test(context): use t.TempDir() in SaveUploadedFile failure test for WSL Mirror the WSL-portability fix applied to TestSaveUploadedFileWithPermission: write under t.TempDir() instead of a relative path so the test does not depend on the working directory's filesystem (drvfs reports 0o777 on WSL) and is cleaned up automatically. Co-Authored-By: Claude Opus 4.8 (1M context) --------- Co-authored-by: Bo-Yi Wu Co-authored-by: Claude Opus 4.8 (1M context) --- context_test.go | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/context_test.go b/context_test.go index 2dfdd392..d93e470f 100644 --- a/context_test.go +++ b/context_test.go @@ -248,13 +248,11 @@ func TestSaveUploadedFileWithPermission(t *testing.T) { require.NoError(t, err) assert.Equal(t, "permission_test", f.Filename) var mode fs.FileMode = 0o755 - require.NoError(t, c.SaveUploadedFile(f, "permission_test", mode)) - t.Cleanup(func() { - assert.NoError(t, os.Remove("permission_test")) - }) - info, err := os.Stat(filepath.Dir("permission_test")) + dst := filepath.Join(t.TempDir(), "subdir", "permission_test") + require.NoError(t, c.SaveUploadedFile(f, dst, mode)) + info, err := os.Stat(filepath.Dir(dst)) require.NoError(t, err) - assert.Equal(t, info.Mode().Perm(), mode) + assert.Equal(t, mode, info.Mode().Perm()) } func TestSaveUploadedFileWithPermissionFailed(t *testing.T) { @@ -272,7 +270,8 @@ func TestSaveUploadedFileWithPermissionFailed(t *testing.T) { require.NoError(t, err) assert.Equal(t, "permission_test", f.Filename) var mode fs.FileMode = 0o644 - require.Error(t, c.SaveUploadedFile(f, "test/permission_test", mode)) + dst := filepath.Join(t.TempDir(), "test", "permission_test") + require.Error(t, c.SaveUploadedFile(f, dst, mode)) } func TestContextReset(t *testing.T) { From d9307dbcbbe796a64d9e0ef23452da888dd7f904 Mon Sep 17 00:00:00 2001 From: Muhammad Ardy Junata Date: Mon, 22 Jun 2026 22:34:41 +0700 Subject: [PATCH 06/27] fix(context): skip chmod on pre-existing dirs in SaveUploadedFile (#4702) * fix: skip chmod on pre-existing dirs in SaveUploadedFile Fixes #4622 Prior to this change, SaveUploadedFile unconditionally called os.Chmod(dir, mode) after os.MkdirAll, even when the target directory already existed. This caused 'operation not permitted' errors when saving files into system-owned directories like /tmp that the current process does not own. The fix uses os.Stat before MkdirAll to detect whether the directory already exists, and only calls os.Chmod when the directory was freshly created by MkdirAll. This restores the behaviour from v1.10.1 where only os.MkdirAll was used (which correctly skips permission changes on existing dirs) while preserving the custom permission feature added in v1.12.0. Regression test added: TestSaveUploadedFileToExistingDir saves a file into os.TempDir() (a pre-existing system directory) and asserts no error is returned. * test: make SaveUploadedFile #4622 regression test platform-independent The regression test relied on os.Chmod failing on a pre-existing directory, which only happens for a non-owner, non-root process. When tests run as root (common in containers/CI) or with a user-owned $TMPDIR, the buggy chmod succeeds, so the test passed even against the unfixed code. Assert the actual contract instead: a pre-existing directory's permissions are left unchanged. This catches the regression deterministically on every platform. Also tighten the SaveUploadedFile doc/comments: the requested perm is enforced only on the newly created destination directory, not on every directory in the path. Co-Authored-By: Claude Opus 4.8 (1M context) --------- Co-authored-by: Bo-Yi Wu Co-authored-by: Claude Opus 4.8 (1M context) --- context.go | 17 +++++++++++++++-- context_test.go | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/context.go b/context.go index 640e20b2..893edb28 100644 --- a/context.go +++ b/context.go @@ -726,6 +726,11 @@ func (c *Context) MultipartForm() (*multipart.Form, error) { } // SaveUploadedFile uploads the form file to specific dst. +// An optional perm argument specifies the permission bits used when creating +// the destination directory. If not provided, the default is 0750. The exact +// permission is enforced only on the destination directory and only when it is +// newly created by this call; pre-existing directories (e.g. /tmp) are not +// modified. func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string, perm ...fs.FileMode) error { src, err := file.Open() if err != nil { @@ -738,11 +743,19 @@ func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string, perm mode = perm[0] } dir := filepath.Dir(dst) + // Record whether the destination directory exists before MkdirAll, so we + // only chmod a directory we just created. Chmod'ing a pre-existing directory + // the process does not own (e.g. /tmp) fails with "operation not permitted" + // (#4622). A non-ErrNotExist stat error also skips chmod and lets MkdirAll + // surface the underlying failure. + _, statErr := os.Stat(dir) if err = os.MkdirAll(dir, mode); err != nil { return err } - if err = os.Chmod(dir, mode); err != nil { - return err + if errors.Is(statErr, os.ErrNotExist) { + if err = os.Chmod(dir, mode); err != nil { + return err + } } out, err := os.Create(dst) diff --git a/context_test.go b/context_test.go index d93e470f..e8d305e4 100644 --- a/context_test.go +++ b/context_test.go @@ -274,6 +274,50 @@ func TestSaveUploadedFileWithPermissionFailed(t *testing.T) { require.Error(t, c.SaveUploadedFile(f, dst, mode)) } +// TestSaveUploadedFileToExistingDir is a regression test for issue #4622. +// SaveUploadedFile must not call os.Chmod on a directory that already exists, +// because the process may not own it (e.g. /tmp on Linux/macOS), where chmod +// fails with "operation not permitted". This asserts the behavioral contract +// directly — a pre-existing directory's permissions are left unchanged — so it +// catches the regression on every platform, including environments (root/CI, +// user-owned $TMPDIR) where chmod on the temp dir would otherwise succeed. +func TestSaveUploadedFileToExistingDir(t *testing.T) { + buf := new(bytes.Buffer) + mw := multipart.NewWriter(buf) + w, err := mw.CreateFormFile("file", "existing_dir_test") + require.NoError(t, err) + _, err = w.Write([]byte("existing_dir_test")) + require.NoError(t, err) + mw.Close() + + c, _ := CreateTestContext(httptest.NewRecorder()) + c.Request, _ = http.NewRequest(http.MethodPost, "/", buf) + c.Request.Header.Set("Content-Type", mw.FormDataContentType()) + f, err := c.FormFile("file") + require.NoError(t, err) + + // A pre-existing directory owned by this process, set to a known mode. + dir := t.TempDir() + require.NoError(t, os.Chmod(dir, 0o700)) + + // Pass a perm that differs from the directory's current mode. The fix must + // not apply it to the pre-existing directory; the old code chmod'd it + // unconditionally, which also failed outright on unowned dirs like /tmp. + dst := filepath.Join(dir, "existing_dir_test.txt") + require.NoError(t, c.SaveUploadedFile(f, dst, 0o755)) + + // The pre-existing directory's permissions must be unchanged. + info, err := os.Stat(dir) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o700), info.Mode().Perm(), + "permissions of a pre-existing directory must not be modified") + + // The file must still be written with the correct content. + content, err := os.ReadFile(dst) + require.NoError(t, err) + assert.Equal(t, "existing_dir_test", string(content)) +} + func TestContextReset(t *testing.T) { router := New() c := router.allocateContext(0) From 03f3e420a3c370659359fb4deb99a474229b215a Mon Sep 17 00:00:00 2001 From: Hershel1995 Date: Tue, 23 Jun 2026 14:08:30 +0200 Subject: [PATCH 07/27] update validator library to version 10.30.3 (#4707) Co-authored-by: Carmelo Sottile --- go.mod | 4 ++-- go.sum | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index 705034ee..4421641e 100644 --- a/go.mod +++ b/go.mod @@ -5,7 +5,7 @@ go 1.25.0 require ( github.com/bytedance/sonic v1.15.0 github.com/gin-contrib/sse v1.1.0 - github.com/go-playground/validator/v10 v10.30.1 + github.com/go-playground/validator/v10 v10.30.3 github.com/goccy/go-json v0.10.6 github.com/goccy/go-yaml v1.19.2 github.com/json-iterator/go v1.1.12 @@ -39,7 +39,7 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect go.uber.org/mock v0.6.0 // indirect golang.org/x/arch v0.25.0 // indirect - golang.org/x/crypto v0.51.0 // indirect + golang.org/x/crypto v0.52.0 // indirect golang.org/x/sys v0.45.0 // indirect golang.org/x/text v0.37.0 // indirect ) diff --git a/go.sum b/go.sum index c38e6eae..a83985ba 100644 --- a/go.sum +++ b/go.sum @@ -20,8 +20,8 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= -github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= -github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= +github.com/go-playground/validator/v10 v10.30.3 h1:4MU6YkEwx7GbcPJOZxrtbu+QfF3pJLJuaYTeAH0DYy8= +github.com/go-playground/validator/v10 v10.30.3/go.mod h1:4Axh7oCNGcoGkqLoE4YWt6n20mcEIsPRlB7vPk3lpyc= github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU= github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= @@ -79,8 +79,8 @@ go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= golang.org/x/arch v0.25.0 h1:qnk6Ksugpi5Bz32947rkUgDt9/s5qvqDPl/gBKdMJLE= golang.org/x/arch v0.25.0/go.mod h1:0X+GdSIP+kL5wPmpK7sdkEVTt2XoYP0cSjQSbZBwOi8= -golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI= -golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8= +golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= +golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= From 34dac209ffb6ef85cc78c5d217bbb7ad001d68fd Mon Sep 17 00:00:00 2001 From: greymoth Date: Sat, 27 Jun 2026 01:48:16 +0900 Subject: [PATCH 08/27] docs: fix `BindXML` comment referencing nonexistent `binding.BindXML` (#4717) The doc comment on line 790 read: "BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML)." `binding.BindXML` does not exist. The correct symbol is `binding.XML` (defined in binding/binding.go), which is also what the implementation uses. All sibling methods (BindJSON, BindYAML, BindTOML, etc.) already reference the correct symbol in their comments. --- context.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/context.go b/context.go index 893edb28..1dc730e3 100644 --- a/context.go +++ b/context.go @@ -787,7 +787,7 @@ func (c *Context) BindJSON(obj any) error { return c.MustBindWith(obj, binding.JSON) } -// BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML). +// BindXML is a shortcut for c.MustBindWith(obj, binding.XML). func (c *Context) BindXML(obj any) error { return c.MustBindWith(obj, binding.XML) } From 00cfe5aac2604e0632ee674b69a1e652a2461923 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 15 Aug 2026 13:42:11 +0800 Subject: [PATCH 09/27] chore(deps): bump the actions group across 1 directory with 4 updates (#4787) Bumps the actions group with 4 updates in the / directory: [actions/checkout](https://github.com/actions/checkout), [actions/setup-go](https://github.com/actions/setup-go), [actions/cache](https://github.com/actions/cache) and [codecov/codecov-action](https://github.com/codecov/codecov-action). Updates `actions/checkout` from 6 to 7 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v6...v7) Updates `actions/setup-go` from 6 to 7 - [Release notes](https://github.com/actions/setup-go/releases) - [Commits](https://github.com/actions/setup-go/compare/v6...v7) Updates `actions/cache` from 5 to 6 - [Release notes](https://github.com/actions/cache/releases) - [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md) - [Commits](https://github.com/actions/cache/compare/v5...v6) Updates `codecov/codecov-action` from 6 to 7 - [Release notes](https://github.com/codecov/codecov-action/releases) - [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/codecov/codecov-action/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: actions/setup-go dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: actions/cache dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions - dependency-name: codecov/codecov-action dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major dependency-group: actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/codeql.yml | 2 +- .github/workflows/gin.yml | 12 ++++++------ .github/workflows/goreleaser.yml | 4 ++-- .github/workflows/trivy-scan.yml | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index f287c265..0ede2a05 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -33,7 +33,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@v7 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL diff --git a/.github/workflows/gin.yml b/.github/workflows/gin.yml index 8857bebc..072312dd 100644 --- a/.github/workflows/gin.yml +++ b/.github/workflows/gin.yml @@ -16,11 +16,11 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v6 + uses: actions/setup-go@v7 with: go-version: "^1" - name: Setup golangci-lint @@ -55,17 +55,17 @@ jobs: GOPROXY: https://proxy.golang.org steps: - name: Set up Go ${{ matrix.go }} - uses: actions/setup-go@v6 + uses: actions/setup-go@v7 with: go-version: ${{ matrix.go }} cache: false - name: Checkout Code - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: ref: ${{ github.ref }} - - uses: actions/cache@v5 + - uses: actions/cache@v6 with: path: | ${{ matrix.go-build }} @@ -78,6 +78,6 @@ jobs: run: make test - name: Upload coverage to Codecov - uses: codecov/codecov-action@v6 + uses: codecov/codecov-action@v7 with: flags: ${{ matrix.os }},go-${{ matrix.go }},${{ matrix.test-tags }} diff --git a/.github/workflows/goreleaser.yml b/.github/workflows/goreleaser.yml index ea933e7e..6dd36ff1 100644 --- a/.github/workflows/goreleaser.yml +++ b/.github/workflows/goreleaser.yml @@ -13,11 +13,11 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@v6 + uses: actions/setup-go@v7 with: go-version: "^1" - name: Run GoReleaser diff --git a/.github/workflows/trivy-scan.yml b/.github/workflows/trivy-scan.yml index 9060e45c..751d0106 100644 --- a/.github/workflows/trivy-scan.yml +++ b/.github/workflows/trivy-scan.yml @@ -22,7 +22,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 0 From 8dd20118ba9a9dfa18ebba99e33d6a59b0090436 Mon Sep 17 00:00:00 2001 From: Gaurav Patil <159000263+GP-09@users.noreply.github.com> Date: Sat, 15 Aug 2026 11:13:07 +0530 Subject: [PATCH 10/27] fix(deps): bump golang.org/x/net and golang.org/x/text to patched versions (#4807) The scheduled Trivy scan has been failing on master with two HIGH findings, and it fails every pull request along with it: - CVE-2026-56852, golang.org/x/text, denial of service, fixed in 0.39.0 - CVE-2026-46600, golang.org/x/net/dns/dnsmessage, denial of service, fixed in 0.56.0 Bump both to the first patched release. golang.org/x/crypto and golang.org/x/sys move with them as transitive requirements of x/net. Verified with the same settings the workflow uses: trivy fs --scanners vuln --severity CRITICAL,HIGH,MEDIUM \ --ignore-unfixed --exit-code 1 . which now exits 0. go build ./... and go test ./... pass. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Bo-Yi Wu --- go.mod | 8 ++++---- go.sum | 16 ++++++++-------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/go.mod b/go.mod index 4421641e..3f80e1c0 100644 --- a/go.mod +++ b/go.mod @@ -16,7 +16,7 @@ require ( github.com/stretchr/testify v1.11.1 github.com/ugorji/go/codec v1.3.1 go.mongodb.org/mongo-driver/v2 v2.5.0 - golang.org/x/net v0.55.0 + golang.org/x/net v0.56.0 google.golang.org/protobuf v1.36.11 ) @@ -39,7 +39,7 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect go.uber.org/mock v0.6.0 // indirect golang.org/x/arch v0.25.0 // indirect - golang.org/x/crypto v0.52.0 // indirect - golang.org/x/sys v0.45.0 // indirect - golang.org/x/text v0.37.0 // indirect + golang.org/x/crypto v0.53.0 // indirect + golang.org/x/sys v0.46.0 // indirect + golang.org/x/text v0.39.0 // indirect ) diff --git a/go.sum b/go.sum index a83985ba..f04ab19c 100644 --- a/go.sum +++ b/go.sum @@ -79,15 +79,15 @@ go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= golang.org/x/arch v0.25.0 h1:qnk6Ksugpi5Bz32947rkUgDt9/s5qvqDPl/gBKdMJLE= golang.org/x/arch v0.25.0/go.mod h1:0X+GdSIP+kL5wPmpK7sdkEVTt2XoYP0cSjQSbZBwOi8= -golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= -golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= -golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= -golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= +golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= +golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= +golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= -golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= -golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= +golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus= +golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= From dcaa4296d111981ffb31ac3eba90bb63e1eb5ab9 Mon Sep 17 00:00:00 2001 From: Amirhf Date: Sat, 15 Aug 2026 09:14:19 +0330 Subject: [PATCH 11/27] docs(path): fix malformed comment in cleanPath (#4723) --- path.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/path.go b/path.go index 3b67caa9..672213d1 100644 --- a/path.go +++ b/path.go @@ -55,7 +55,7 @@ func cleanPath(p string) string { // A bit more clunky without a 'lazybuf' like the path package, but the loop // gets completely inlined (bufApp calls). - // loop has no expensive function calls (except 1x make) // So in contrast to the path package this loop has no expensive function + // So in contrast to the path package this loop has no expensive function // calls (except make, if needed). for r < n { From 2a1a14ff37a26ca6a76763ecc33727c23d9284e9 Mon Sep 17 00:00:00 2001 From: Jia-ben00 <2403877005@qq.com> Date: Wed, 16 Sep 2026 21:24:33 +0800 Subject: [PATCH 12/27] feat(router): add QUERY method shortcut for RFC 10008 (#4830) * feat(router): add QUERY method shortcut for RFC 10008 Add a QUERY() router method as a shortcut for Handle("QUERY", path, handlers), following the same pattern as GET, POST, HEAD and other HTTP method shortcuts. The QUERY method is defined by RFC 10008 and allows sending a query in the request body, similar to GET but with a body. Go's net/http does not yet expose an http.MethodQuery constant, so the literal string "QUERY" is used. Closes #4721 * style(router): format QUERY method test - Remove an extra blank line to satisfy gofmt. --------- Co-authored-by: Jia-ben00 <316397950+Jia-ben00@users.noreply.github.com> Co-authored-by: Bo-Yi Wu --- gin_test.go | 19 +++++++++++++++++++ routergroup.go | 7 +++++++ 2 files changed, 26 insertions(+) diff --git a/gin_test.go b/gin_test.go index a9cf1755..b488c446 100644 --- a/gin_test.go +++ b/gin_test.go @@ -1156,3 +1156,22 @@ func TestUpdateRouteTreesCalledOnce(t *testing.T) { assert.Equal(t, "ok", w.Body.String()) } } + +func TestRouterQueryMethod(t *testing.T) { + router := New() + router.QUERY("/test", func(c *Context) { + c.String(http.StatusOK, "query ok") + }) + + w := httptest.NewRecorder() + req, _ := http.NewRequest("QUERY", "/test", nil) + router.ServeHTTP(w, req) + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "query ok", w.Body.String()) + + // Other methods should not match + w2 := httptest.NewRecorder() + req2, _ := http.NewRequest(http.MethodGet, "/test", nil) + router.ServeHTTP(w2, req2) + assert.Equal(t, http.StatusNotFound, w2.Code) +} diff --git a/routergroup.go b/routergroup.go index c01b917e..1ae0b7b4 100644 --- a/routergroup.go +++ b/routergroup.go @@ -142,6 +142,13 @@ func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRo return group.handle(http.MethodHead, relativePath, handlers) } +// QUERY is a shortcut for router.Handle("QUERY", path, handlers). +// The QUERY method is defined by RFC 10008 and is used to send a query +// in the request body, similar to GET but with a body. +func (group *RouterGroup) QUERY(relativePath string, handlers ...HandlerFunc) IRoutes { + return group.handle("QUERY", relativePath, handlers) +} + // Any registers a route that matches all the HTTP methods. // GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE. func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { From b52df1fe77734c691acc1fce21647fe0ca955201 Mon Sep 17 00:00:00 2001 From: Ruben Pari <73421813+RubenPari@users.noreply.github.com> Date: Wed, 16 Sep 2026 15:26:35 +0200 Subject: [PATCH 13/27] docs: document panic conditions in Handle, StaticFS, and Bind (#4797) Handle panics on invalid HTTP method, StaticFS panics when relativePath contains URL parameters, and Bind panics when given a pointer. These panic conditions are reasonable startup-time guards but were not documented, making the crash risk undiscoverable without reading source. Fixes #4594 --- routergroup.go | 3 +++ utils.go | 1 + 2 files changed, 4 insertions(+) diff --git a/routergroup.go b/routergroup.go index 1ae0b7b4..84d3e00b 100644 --- a/routergroup.go +++ b/routergroup.go @@ -100,6 +100,8 @@ func (group *RouterGroup) handle(httpMethod, relativePath string, handlers Handl // This function is intended for bulk loading and to allow the usage of less // frequently used, non-standardized or custom methods (e.g. for internal // communication with a proxy). +// +// It panics if httpMethod is not a valid HTTP method (uppercase ASCII letters only). func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes { if matched := regEnLetter.MatchString(httpMethod); !matched { panic("http method " + httpMethod + " is not valid") @@ -207,6 +209,7 @@ func (group *RouterGroup) Static(relativePath, root string) IRoutes { // StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead. // Gin by default uses: gin.Dir() +// It panics if relativePath contains URL parameters (: or *). func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes { if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") { panic("URL parameters can not be used when serving a static folder") diff --git a/utils.go b/utils.go index 2fecce46..ac221def 100644 --- a/utils.go +++ b/utils.go @@ -26,6 +26,7 @@ const localhostIP = "127.0.0.1" const localhostIPv6 = "::1" // Bind is a helper function for given interface object and returns a Gin middleware. +// It panics if val is a pointer; pass the struct value directly (e.g., gin.Bind(Struct{}) not gin.Bind(&Struct{})). func Bind(val any) HandlerFunc { value := reflect.ValueOf(val) if value.Kind() == reflect.Ptr { From bc141b4dbf90d5bb5028fc68afe48782402bb2d4 Mon Sep 17 00:00:00 2001 From: Bo-Yi Wu Date: Wed, 16 Sep 2026 22:47:17 +0800 Subject: [PATCH 14/27] fix(deps)!: patch x/crypto vulnerabilities (#4832) - Upgrade x/crypto and its required dependency versions - Align documentation and CI with the required Go version BREAKING CHANGE: Go 1.26 or later is now required by x/crypto v0.56.0. Upgrade the Go toolchain before building Gin. --- .github/workflows/gin.yml | 2 +- README.md | 2 +- go.mod | 10 +++++----- go.sum | 16 ++++++++-------- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/.github/workflows/gin.yml b/.github/workflows/gin.yml index 072312dd..eb463fee 100644 --- a/.github/workflows/gin.yml +++ b/.github/workflows/gin.yml @@ -33,7 +33,7 @@ jobs: strategy: matrix: os: [ubuntu-latest, macos-latest] - go: ["1.25", "1.26"] + go: ["1.26", "1.27"] test-tags: [ "", diff --git a/README.md b/README.md index 96b0ae3c..10e627fc 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ Gin combines the simplicity of Express.js-style routing with Go's performance ch ### Prerequisites -- **Go version**: Gin requires [Go](https://go.dev/) version [1.25](https://go.dev/doc/devel/release#go1.25.0) or above +- **Go version**: Gin requires [Go](https://go.dev/) version [1.26](https://go.dev/doc/devel/release#go1.26.0) or above - **Basic Go knowledge**: Familiarity with Go syntax and package management is helpful ### Installation diff --git a/go.mod b/go.mod index 3f80e1c0..5ede85b2 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/gin-gonic/gin -go 1.25.0 +go 1.26.0 require ( github.com/bytedance/sonic v1.15.0 @@ -16,7 +16,7 @@ require ( github.com/stretchr/testify v1.11.1 github.com/ugorji/go/codec v1.3.1 go.mongodb.org/mongo-driver/v2 v2.5.0 - golang.org/x/net v0.56.0 + golang.org/x/net v0.57.0 google.golang.org/protobuf v1.36.11 ) @@ -39,7 +39,7 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect go.uber.org/mock v0.6.0 // indirect golang.org/x/arch v0.25.0 // indirect - golang.org/x/crypto v0.53.0 // indirect - golang.org/x/sys v0.46.0 // indirect - golang.org/x/text v0.39.0 // indirect + golang.org/x/crypto v0.56.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.41.0 // indirect ) diff --git a/go.sum b/go.sum index f04ab19c..a714fd58 100644 --- a/go.sum +++ b/go.sum @@ -79,15 +79,15 @@ go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= golang.org/x/arch v0.25.0 h1:qnk6Ksugpi5Bz32947rkUgDt9/s5qvqDPl/gBKdMJLE= golang.org/x/arch v0.25.0/go.mod h1:0X+GdSIP+kL5wPmpK7sdkEVTt2XoYP0cSjQSbZBwOi8= -golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= -golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= -golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= -golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y= +golang.org/x/crypto v0.56.0/go.mod h1:OMW5y6CY9l38uPLmxU6l6pwcXp1obtLo3e6gT7gQR2I= +golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE= +golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= -golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= -golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus= -golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= From 5c6a15f8f9566612076bd209e623861bf92a6283 Mon Sep 17 00:00:00 2001 From: Langning Zhang Date: Wed, 16 Sep 2026 23:01:52 +0800 Subject: [PATCH 15/27] fix(context): handle missing HTML renderer (#4805) * fix(context): handle missing HTML renderer * test(render): cover missing HTML renderer error --------- Co-authored-by: Bo-Yi Wu --- context.go | 5 +++ context_test.go | 76 +++++++++++++++++++++++++++++++++++++++++++ render/html.go | 6 ++++ render/render_test.go | 10 ++++++ 4 files changed, 97 insertions(+) diff --git a/context.go b/context.go index 1dc730e3..788b00bb 100644 --- a/context.go +++ b/context.go @@ -1219,6 +1219,11 @@ func (c *Context) Render(code int, r render.Render) { // It also updates the HTTP code and sets the Content-Type as "text/html". // See http://golang.org/doc/articles/wiki/ func (c *Context) HTML(code int, name string, obj any) { + if c.engine.HTMLRender == nil { + c.Render(code, render.HTML{}) + return + } + instance := c.engine.HTMLRender.Instance(name, obj) c.Render(code, instance) } diff --git a/context_test.go b/context_test.go index e8d305e4..cef488c9 100644 --- a/context_test.go +++ b/context_test.go @@ -1345,6 +1345,82 @@ func TestContextRenderHTML(t *testing.T) { assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } +func TestContextRenderHTMLWithoutRenderer(t *testing.T) { + tests := []struct { + name string + method string + status int + wantErrors []string + wantAborted bool + wantNextCalled bool + }{ + { + name: "body allowed", + method: http.MethodGet, + status: http.StatusAccepted, + wantErrors: []string{"html renderer is not configured"}, + wantAborted: true, + }, + { + name: "no content", + method: http.MethodGet, + status: http.StatusNoContent, + wantNextCalled: true, + }, + { + name: "not modified", + method: http.MethodGet, + status: http.StatusNotModified, + wantNextCalled: true, + }, + { + name: "head", + method: http.MethodHead, + status: http.StatusOK, + wantErrors: []string{"html renderer is not configured"}, + wantAborted: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := httptest.NewRecorder() + router := New() + var contextErrors []string + var contextAborted bool + nextHandlerCalled := false + + handlers := []HandlerFunc{ + func(c *Context) { + c.HTML(tt.status, "index.tmpl", H{"title": "Main website"}) + contextErrors = c.Errors.Errors() + contextAborted = c.IsAborted() + }, + func(_ *Context) { + nextHandlerCalled = true + }, + } + if tt.method == http.MethodHead { + router.HEAD("/", handlers...) + } else { + router.GET("/", handlers...) + } + + req := httptest.NewRequest(tt.method, "/", nil) + require.NotPanics(t, func() { + router.ServeHTTP(w, req) + }) + + assert.Equal(t, tt.status, w.Code) + assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) + assert.Equal(t, tt.wantErrors, contextErrors) + assert.Equal(t, tt.wantAborted, contextAborted) + assert.Equal(t, tt.wantNextCalled, nextHandlerCalled) + assert.Empty(t, w.Body.String()) + }) + } +} + func TestContextRenderHTML2(t *testing.T) { w := httptest.NewRecorder() c, router := CreateTestContext(w) diff --git a/render/html.go b/render/html.go index 965d84c6..36c8f079 100644 --- a/render/html.go +++ b/render/html.go @@ -5,6 +5,7 @@ package render import ( + "errors" "html/template" "net/http" @@ -50,6 +51,8 @@ type HTML struct { var htmlContentType = []string{"text/html; charset=utf-8"} +var errHTMLRendererNotConfigured = errors.New("html renderer is not configured") + // Instance (HTMLProduction) returns an HTML instance which it realizes Render interface. func (r HTMLProduction) Instance(name string, data any) Render { return HTML{ @@ -88,6 +91,9 @@ func (r HTMLDebug) loadTemplate() *template.Template { // Render (HTML) executes template and writes its result with custom ContentType for response. func (r HTML) Render(w http.ResponseWriter) error { r.WriteContentType(w) + if r.Template == nil { + return errHTMLRendererNotConfigured + } if r.Name == "" { return r.Template.Execute(w, r.Data) diff --git a/render/render_test.go b/render/render_test.go index f63878b9..24815452 100644 --- a/render/render_test.go +++ b/render/render_test.go @@ -630,6 +630,16 @@ func TestRenderHTMLTemplate(t *testing.T) { assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } +func TestRenderHTMLWithoutTemplate(t *testing.T) { + w := httptest.NewRecorder() + + err := (HTML{}).Render(w) + + require.EqualError(t, err, "html renderer is not configured") + assert.Empty(t, w.Body.String()) + assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) +} + func TestRenderHTMLTemplateEmptyName(t *testing.T) { w := httptest.NewRecorder() templ := template.Must(template.New("").Parse(`Hello {{.name}}`)) From 3329b63aa7c0b107dd6d72a74add233fe11485d8 Mon Sep 17 00:00:00 2001 From: Bob Du Date: Sat, 19 Sep 2026 14:09:40 +0800 Subject: [PATCH 16/27] ci(codecov): fix stale comparison base and invalid config (#4823) Signed-off-by: Bob Du Co-authored-by: Bo-Yi Wu --- .github/workflows/gin.yml | 4 ++++ codecov.yml | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/gin.yml b/.github/workflows/gin.yml index eb463fee..d0f42d09 100644 --- a/.github/workflows/gin.yml +++ b/.github/workflows/gin.yml @@ -30,6 +30,9 @@ jobs: args: --verbose test: needs: lint + permissions: + contents: read + id-token: write strategy: matrix: os: [ubuntu-latest, macos-latest] @@ -80,4 +83,5 @@ jobs: - name: Upload coverage to Codecov uses: codecov/codecov-action@v7 with: + use_oidc: true flags: ${{ matrix.os }},go-${{ matrix.go }},${{ matrix.test-tags }} diff --git a/codecov.yml b/codecov.yml index 47782e50..f78e4295 100644 --- a/codecov.yml +++ b/codecov.yml @@ -1,6 +1,7 @@ -coverage: +codecov: require_ci_to_pass: true +coverage: status: project: default: From e318c6add8f947ba3c0db15f782517a9bb6bedc2 Mon Sep 17 00:00:00 2001 From: daixiheguu Date: Sat, 19 Sep 2026 14:10:49 +0800 Subject: [PATCH 17/27] docs: align function comments with names (#4814) Signed-off-by: daixiheguu Co-authored-by: Bo-Yi Wu --- gin_integration_test.go | 1 + render/render_test.go | 4 ++-- response_writer_test.go | 3 ++- routes_test.go | 18 +++++++++--------- tree.go | 6 +++--- utils.go | 3 ++- 6 files changed, 19 insertions(+), 16 deletions(-) diff --git a/gin_integration_test.go b/gin_integration_test.go index 720b140f..da408d9c 100644 --- a/gin_integration_test.go +++ b/gin_integration_test.go @@ -25,6 +25,7 @@ import ( "github.com/stretchr/testify/require" ) +// testRequest sends a request and validates its response. // params[0]=url example:http://127.0.0.1:8080/index (cannot be empty) // params[1]=response status (custom compare status) default:"200 OK" // params[2]=response body (custom compare content) default:"it worked" diff --git a/render/render_test.go b/render/render_test.go index 24815452..a3f90a3f 100644 --- a/render/render_test.go +++ b/render/render_test.go @@ -283,7 +283,7 @@ func TestRenderPureJSON(t *testing.T) { type xmlmap map[string]any -// Allows type H to be used with xml.Marshal +// MarshalXML allows xmlmap to be used with xml.Marshal. func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error { start.Name = xml.Name{ Space: "", @@ -331,7 +331,7 @@ b: type fail struct{} -// Hook MarshalYAML +// MarshalYAML returns an error for YAML rendering failure tests. func (ft *fail) MarshalYAML() (any, error) { return nil, errors.New("fail") } diff --git a/response_writer_test.go b/response_writer_test.go index 03417375..99548431 100644 --- a/response_writer_test.go +++ b/response_writer_test.go @@ -220,7 +220,8 @@ func TestResponseWriterHijackAfterWrite(t *testing.T) { } } -// Test: WebSocket compatibility - allow hijack after WriteHeaderNow(), but block after body data. +// TestResponseWriterHijackAfterWriteHeaderNow verifies that hijacking is allowed after +// WriteHeaderNow but blocked after body data is written. func TestResponseWriterHijackAfterWriteHeaderNow(t *testing.T) { tests := []struct { name string diff --git a/routes_test.go b/routes_test.go index 1cae3fce..1b7570b0 100644 --- a/routes_test.go +++ b/routes_test.go @@ -51,7 +51,7 @@ func testRouteOK(method string, t *testing.T) { assert.True(t, passedAny) } -// TestSingleRouteOK tests that POST route is correctly invoked. +// testRouteNotOK tests that a request with the wrong method returns a not found response. func testRouteNotOK(method string, t *testing.T) { passed := false router := New() @@ -65,7 +65,7 @@ func testRouteNotOK(method string, t *testing.T) { assert.Equal(t, http.StatusNotFound, w.Code) } -// TestSingleRouteOK tests that POST route is correctly invoked. +// testRouteNotOK2 tests that a request with the wrong method returns a method not allowed response. func testRouteNotOK2(method string, t *testing.T) { passed := false router := New() @@ -273,7 +273,7 @@ func TestRouteRedirectFixedPath(t *testing.T) { assert.Equal(t, http.StatusTemporaryRedirect, w.Code) } -// TestContextParamsGet tests that a parameter can be parsed from the URL. +// TestRouteParamsByName tests that route parameters can be parsed by name. func TestRouteParamsByName(t *testing.T) { name := "" lastName := "" @@ -305,7 +305,7 @@ func TestRouteParamsByName(t *testing.T) { assert.Equal(t, "/is/super/great", wild) } -// TestContextParamsGet tests that a parameter can be parsed from the URL even with extra slashes. +// TestRouteParamsByNameWithExtraSlash tests that route parameters can be parsed by name even with extra slashes. func TestRouteParamsByNameWithExtraSlash(t *testing.T) { name := "" lastName := "" @@ -377,7 +377,7 @@ func TestRouteParamsNotEmpty(t *testing.T) { assert.Equal(t, "/is/super/great", wild) } -// TestHandleStaticFile - ensure the static file handles properly +// TestRouteStaticFile tests that a static file is served correctly. func TestRouteStaticFile(t *testing.T) { // SETUP file testRoot, _ := os.Getwd() @@ -412,7 +412,7 @@ func TestRouteStaticFile(t *testing.T) { assert.Equal(t, http.StatusOK, w3.Code) } -// TestHandleStaticFile - ensure the static file handles properly +// TestRouteStaticFileFS tests that a static file from an http.FileSystem is served correctly. func TestRouteStaticFileFS(t *testing.T) { // SETUP file testRoot, _ := os.Getwd() @@ -446,7 +446,7 @@ func TestRouteStaticFileFS(t *testing.T) { assert.Equal(t, http.StatusOK, w3.Code) } -// TestHandleStaticDir - ensure the root/sub dir handles properly +// TestRouteStaticListingDir tests that static directory listing is enabled when configured. func TestRouteStaticListingDir(t *testing.T) { router := New() router.StaticFS("/", Dir("./", true)) @@ -458,7 +458,7 @@ func TestRouteStaticListingDir(t *testing.T) { assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type")) } -// TestHandleHeadToDir - ensure the root/sub dir handles properly +// TestRouteStaticNoListing tests that static directory listing is disabled by default. func TestRouteStaticNoListing(t *testing.T) { router := New() router.Static("/", "./") @@ -656,7 +656,7 @@ func TestRouterStaticFSFileNotFound(t *testing.T) { }) } -// Reproduction test for the bug of issue #1805 +// TestMiddlewareCalledOnceByRouterStaticFSNotFound reproduces the bug reported in issue #1805. func TestMiddlewareCalledOnceByRouterStaticFSNotFound(t *testing.T) { router := New() diff --git a/tree.go b/tree.go index 580abbaf..dc84ff61 100644 --- a/tree.go +++ b/tree.go @@ -107,7 +107,7 @@ type node struct { fullPath string } -// Increments priority of the given child and reorders if necessary +// incrementChildPrio increments the priority of the given child and reorders it if necessary. func (n *node) incrementChildPrio(pos int) int { cs := n.children cs[pos].priority++ @@ -683,7 +683,7 @@ func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) ([]by return ciPath, ciPath != nil } -// Shift bytes in array by n bytes left +// shiftNRuneBytes shifts bytes in the array n positions to the left. func shiftNRuneBytes(rb [4]byte, n int) [4]byte { switch n { case 0: @@ -699,7 +699,7 @@ func shiftNRuneBytes(rb [4]byte, n int) [4]byte { } } -// Recursive case-insensitive lookup function used by n.findCaseInsensitivePath +// findCaseInsensitivePathRec recursively performs a case-insensitive path lookup. func (n *node) findCaseInsensitivePathRec(path string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) []byte { npLen := len(n.path) diff --git a/utils.go b/utils.go index ac221def..e8b86fcc 100644 --- a/utils.go +++ b/utils.go @@ -161,7 +161,8 @@ func resolveAddress(addr []string) string { } } -// https://stackoverflow.com/questions/53069040/checking-a-string-contains-only-ascii-characters +// isASCII reports whether s contains only ASCII characters. +// See https://stackoverflow.com/questions/53069040/checking-a-string-contains-only-ascii-characters. func isASCII(s string) bool { for i := range len(s) { if s[i] > unicode.MaxASCII { From 05b14df992a31fe8ff567338bb6c934f1aa3872f Mon Sep 17 00:00:00 2001 From: Bob Du Date: Sat, 19 Sep 2026 14:12:33 +0800 Subject: [PATCH 18/27] chore(deps): bump github.com/stretchr/testify to v1.12.1 (#4822) Signed-off-by: Bob Du Co-authored-by: Bo-Yi Wu --- go.mod | 8 ++------ go.sum | 17 ++++------------- 2 files changed, 6 insertions(+), 19 deletions(-) diff --git a/go.mod b/go.mod index 5ede85b2..99a8d5bb 100644 --- a/go.mod +++ b/go.mod @@ -13,31 +13,27 @@ require ( github.com/modern-go/reflect2 v1.0.2 github.com/pelletier/go-toml/v2 v2.2.4 github.com/quic-go/quic-go v0.60.0 - github.com/stretchr/testify v1.11.1 + github.com/stretchr/testify v1.12.1 github.com/ugorji/go/codec v1.3.1 go.mongodb.org/mongo-driver/v2 v2.5.0 golang.org/x/net v0.57.0 google.golang.org/protobuf v1.36.11 ) -require gopkg.in/yaml.v3 v3.0.1 // indirect - require ( github.com/bytedance/gopkg v0.1.3 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect github.com/cloudwego/base64x v0.1.6 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect github.com/gabriel-vasile/mimetype v1.4.13 // indirect github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/klauspost/cpuid/v2 v2.3.0 // indirect - github.com/kr/text v0.2.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/pmezard/go-difflib v1.0.0 // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect go.uber.org/mock v0.6.0 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/arch v0.25.0 // indirect golang.org/x/crypto v0.56.0 // indirect golang.org/x/sys v0.47.0 // indirect diff --git a/go.sum b/go.sum index a714fd58..dc6ef902 100644 --- a/go.sum +++ b/go.sum @@ -6,7 +6,6 @@ github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiD github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -33,10 +32,6 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= -github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= -github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= @@ -48,7 +43,6 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/quic-go/go-ossfuzz-seeds v0.1.0 h1:APacT+iIaNF6fd8AGEiN3bT/Jtkd2jz4v4TzM7MFjy0= github.com/quic-go/go-ossfuzz-seeds v0.1.0/go.mod h1:3IOHRbJIc+L6YKMwfDtJAM9Vj9k0YY4muhuyUYk5tbk= @@ -56,8 +50,6 @@ github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/quic-go v0.60.0 h1:xcQioE8OM66UQLeUMHltK1CCcOu3JbVB4JAQdDQSB+0= github.com/quic-go/quic-go v0.60.0/go.mod h1:wpKpjmPpftl30sL6pFh7REVpjbcCVy4zt2vDyK1TuJk= -github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= -github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -67,8 +59,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= @@ -77,6 +69,8 @@ go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= golang.org/x/arch v0.25.0 h1:qnk6Ksugpi5Bz32947rkUgDt9/s5qvqDPl/gBKdMJLE= golang.org/x/arch v0.25.0/go.mod h1:0X+GdSIP+kL5wPmpK7sdkEVTt2XoYP0cSjQSbZBwOi8= golang.org/x/crypto v0.56.0 h1:GUh5Ii4J5jtcseSMiRqr1jXCNHoxjeV9Fmekc2oLy6Y= @@ -91,8 +85,5 @@ golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= From b1f77cf536154f67e3332fc5d0965b891be86606 Mon Sep 17 00:00:00 2001 From: Gaurav Patil <159000263+GP-09@users.noreply.github.com> Date: Sat, 19 Sep 2026 11:50:37 +0530 Subject: [PATCH 19/27] feat(gin): add support for the HTTP QUERY method (RFC 10008) (#4806) * feat: add support for the HTTP QUERY method (RFC 10008) Add a QUERY shortcut on RouterGroup, a gin.MethodQuery constant and a gin.IQueryRoutes interface for callers that only hold an IRoutes value. QUERY is deliberately kept out of IRoutes and out of Any: - Adding a method to IRoutes would break every type outside of Gin that implements it, such as test doubles and wrappers. - Leaving Any untouched keeps existing catch-all routes matching exactly the methods they matched before. Match([]string{gin.MethodQuery, ...}) covers the case where QUERY is wanted alongside other methods. MethodQuery is declared in Gin because the standard library does not provide http.MethodQuery yet. The value stays correct once it does. Ref #4721 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix(router): remove duplicate QUERY method - Consolidate QUERY into the existing router method after merging master - Preserve the MethodQuery constant and request body documentation --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Bo-Yi Wu --- docs/doc.md | 41 +++++++++++++++++++++++++++++++++ ginS/gins.go | 5 +++++ ginS/gins_test.go | 13 +++++++++++ routergroup.go | 38 +++++++++++++++++++++++++++---- routergroup_test.go | 4 ++++ routes_test.go | 55 +++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 152 insertions(+), 4 deletions(-) diff --git a/docs/doc.md b/docs/doc.md index d1c33b87..b635335e 100644 --- a/docs/doc.md +++ b/docs/doc.md @@ -7,6 +7,7 @@ - [Build without MsgPack rendering feature](#build-without-msgpack-rendering-feature) - [Routing](#routing) - [Using GET, POST, PUT, PATCH, DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options) + - [Using the QUERY method](#using-the-query-method) - [Parameters in path](#parameters-in-path) - [Querystring parameters](#querystring-parameters) - [Multipart/Urlencoded Form](#multiparturlencoded-form) @@ -137,6 +138,46 @@ func main() { } ``` +### Using the QUERY method + +`QUERY` is the safe and idempotent method defined by [RFC 10008](https://www.rfc-editor.org/info/rfc10008/). It carries its query in the request body, so you can send a query that is too large or too structured for a URL without turning it into a `POST`. + +```go +func main() { + router := gin.Default() + + router.QUERY("/search", func(c *gin.Context) { + var query struct { + Term string `json:"term"` + } + if err := c.ShouldBindJSON(&query); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, gin.H{"term": query.Term}) + }) + + router.Run() +} +``` + +Use the `gin.MethodQuery` constant wherever an HTTP method name is expected, for example when building a request in a test: + +```go +req := httptest.NewRequest(gin.MethodQuery, "/search", body) +``` + +Two things to keep in mind: + +- `router.Any` does not register `QUERY`, so existing catch-all routes keep matching exactly the methods they matched before. Use `router.QUERY` or `router.Match([]string{gin.MethodQuery, http.MethodPost}, ...)` when you want it. +- `QUERY` is not part of the `gin.IRoutes` interface. `*gin.Engine` and `*gin.RouterGroup` expose it directly; if you only hold an `IRoutes` value, assert to `gin.IQueryRoutes` first. + +```go +if q, ok := routes.(gin.IQueryRoutes); ok { + q.QUERY("/search", searching) +} +``` + ### Parameters in path ```go diff --git a/ginS/gins.go b/ginS/gins.go index 7918ce3a..5a82ab09 100644 --- a/ginS/gins.go +++ b/ginS/gins.go @@ -67,6 +67,11 @@ func GET(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().GET(relativePath, handlers...) } +// QUERY is a shortcut for router.Handle("QUERY", path, handle) +func QUERY(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { + return engine().QUERY(relativePath, handlers...) +} + // DELETE is a shortcut for router.Handle("DELETE", path, handle) func DELETE(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes { return engine().DELETE(relativePath, handlers...) diff --git a/ginS/gins_test.go b/ginS/gins_test.go index ffde85d2..d7f0d624 100644 --- a/ginS/gins_test.go +++ b/ginS/gins_test.go @@ -31,6 +31,19 @@ func TestGET(t *testing.T) { assert.Equal(t, "test", w.Body.String()) } +func TestQUERY(t *testing.T) { + QUERY("/query", func(c *gin.Context) { + c.String(http.StatusOK, "query") + }) + + req := httptest.NewRequest(gin.MethodQuery, "/query", nil) + w := httptest.NewRecorder() + engine().ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "query", w.Body.String()) +} + func TestPOST(t *testing.T) { POST("/post", func(c *gin.Context) { c.String(http.StatusCreated, "created") diff --git a/routergroup.go b/routergroup.go index 84d3e00b..d85a8baf 100644 --- a/routergroup.go +++ b/routergroup.go @@ -11,6 +11,11 @@ import ( "strings" ) +// MethodQuery is the HTTP QUERY method defined by RFC 10008. It is declared +// here because the standard library does not provide http.MethodQuery yet. +// Once it does, this constant keeps the same value and stays valid. +const MethodQuery = "QUERY" + var ( // regEnLetter matches english letters for http method name regEnLetter = regexp.MustCompile("^[A-Z]+$") @@ -50,6 +55,22 @@ type IRoutes interface { StaticFS(string, http.FileSystem) IRoutes } +// IQueryRoutes defines the router handle interface for the HTTP QUERY method. +// +// It is deliberately kept out of IRoutes: adding a method to IRoutes would +// break every type outside of Gin that implements it, such as test doubles and +// wrappers. Type assert when you only hold an IRoutes value: +// +// if q, ok := routes.(gin.IQueryRoutes); ok { +// q.QUERY("/search", handler) +// } +// +// *gin.RouterGroup and *gin.Engine satisfy this interface, so the assertion is +// only needed when the concrete type has been erased. +type IQueryRoutes interface { + QUERY(string, ...HandlerFunc) IRoutes +} + // RouterGroup is used internally to configure router, a RouterGroup is associated with // a prefix and an array of handlers (middleware). type RouterGroup struct { @@ -59,7 +80,10 @@ type RouterGroup struct { root bool } -var _ IRouter = (*RouterGroup)(nil) +var ( + _ IRouter = (*RouterGroup)(nil) + _ IQueryRoutes = (*RouterGroup)(nil) +) // Use adds middleware to the group, see example code in GitHub. func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes { @@ -145,14 +169,20 @@ func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRo } // QUERY is a shortcut for router.Handle("QUERY", path, handlers). -// The QUERY method is defined by RFC 10008 and is used to send a query -// in the request body, similar to GET but with a body. +// +// QUERY is the safe and idempotent method defined by RFC 10008 that carries its +// query in the request body. The body is read like any other body, for example +// with c.ShouldBindJSON. func (group *RouterGroup) QUERY(relativePath string, handlers ...HandlerFunc) IRoutes { - return group.handle("QUERY", relativePath, handlers) + return group.handle(MethodQuery, relativePath, handlers) } // Any registers a route that matches all the HTTP methods. // GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE. +// +// QUERY is not part of that list, so that Any keeps registering exactly the +// same routes as before. Register it with QUERY, or with +// Match([]string{gin.MethodQuery, ...}, ...) to combine it with other methods. func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { for _, method := range anyMethods { group.handle(method, relativePath, handlers) diff --git a/routergroup_test.go b/routergroup_test.go index 182c5589..be5c7819 100644 --- a/routergroup_test.go +++ b/routergroup_test.go @@ -42,6 +42,7 @@ func TestRouterGroupBasicHandle(t *testing.T) { performRequestInGroup(t, http.MethodDelete) performRequestInGroup(t, http.MethodHead) performRequestInGroup(t, http.MethodOptions) + performRequestInGroup(t, MethodQuery) } func performRequestInGroup(t *testing.T, method string) { @@ -78,6 +79,9 @@ func performRequestInGroup(t *testing.T, method string) { case http.MethodOptions: v1.OPTIONS("/test", handler) login.OPTIONS("/test", handler) + case MethodQuery: + v1.QUERY("/test", handler) + login.QUERY("/test", handler) default: panic("unknown method") } diff --git a/routes_test.go b/routes_test.go index 1b7570b0..e9a89252 100644 --- a/routes_test.go +++ b/routes_test.go @@ -10,6 +10,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "strings" "testing" "github.com/stretchr/testify/assert" @@ -86,6 +87,60 @@ func testRouteNotOK2(method string, t *testing.T) { assert.Equal(t, http.StatusMethodNotAllowed, w.Code) } +// TestRouteQuery tests that a QUERY route is invoked and can read the request +// body, which is the whole point of the method (RFC 10008). +func TestRouteQuery(t *testing.T) { + type search struct { + Term string `json:"term"` + } + + router := New() + router.QUERY("/search", func(c *Context) { + var body search + require.NoError(t, c.ShouldBindJSON(&body)) + c.String(http.StatusOK, body.Term) + }) + + req := httptest.NewRequest(MethodQuery, "/search", strings.NewReader(`{"term":"gin"}`)) + req.Header.Set("Content-Type", MIMEJSON) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "gin", w.Body.String()) +} + +// TestRouteQueryNotRegisteredByAny documents that Any does not register QUERY, +// so that existing Any routes keep matching exactly the methods they used to. +func TestRouteQueryNotRegisteredByAny(t *testing.T) { + router := New() + router.Any("/test", func(c *Context) { + c.Status(http.StatusOK) + }) + + w := PerformRequest(router, MethodQuery, "/test") + + assert.Equal(t, http.StatusNotFound, w.Code) +} + +// TestQueryRoutesInterface tests that a router reached through IRoutes can +// still register a QUERY route via the IQueryRoutes assertion. +func TestQueryRoutesInterface(t *testing.T) { + router := New() + + var routes IRoutes = router.Group("/v1") + queryRoutes, ok := routes.(IQueryRoutes) + require.True(t, ok) + + queryRoutes.QUERY("/search", func(c *Context) { + c.Status(http.StatusOK) + }) + + w := PerformRequest(router, MethodQuery, "/v1/search") + + assert.Equal(t, http.StatusOK, w.Code) +} + func TestRouterMethod(t *testing.T) { router := New() router.PUT("/hey2", func(c *Context) { From 8ad9f9cbeab45887327608f393bb614187e06099 Mon Sep 17 00:00:00 2001 From: Wahid Rizka Fathurrohman <58039870+wahidrizka@users.noreply.github.com> Date: Sat, 19 Sep 2026 13:21:21 +0700 Subject: [PATCH 20/27] docs: fix the graceful shutdown example (#4809) The example calls errors.Is but never imports errors, so copying it as written fails to build with "undefined: errors". It also passes an unbuffered channel to signal.Notify, which go vet reports as a misuse: signal delivery is non-blocking, so a signal that arrives before the receive is dropped. --- docs/doc.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/doc.md b/docs/doc.md index b635335e..3f0c94ea 100644 --- a/docs/doc.md +++ b/docs/doc.md @@ -2399,6 +2399,7 @@ package main import ( "context" + "errors" "log" "net/http" "os" @@ -2431,7 +2432,7 @@ func main() { // Wait for interrupt signal to gracefully shutdown the server with // a timeout of 5 seconds. - quit := make(chan os.Signal) + quit := make(chan os.Signal, 1) // kill (no param) default send syscall.SIGTERM // kill -2 is syscall.SIGINT // kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it From d8f2d588d7573b3438cfc95b7a47f9ec8966273c Mon Sep 17 00:00:00 2001 From: Ruben Pari <73421813+RubenPari@users.noreply.github.com> Date: Sat, 19 Sep 2026 08:41:53 +0200 Subject: [PATCH 21/27] fix(engine): add default ReadHeaderTimeout to http.Server in Run methods (#4800) Engine.Run, RunTLS, and RunListener created an http.Server without ReadHeaderTimeout, leaving applications exposed to slowloris-style resource exhaustion. A new Engine.ReadHeaderTimeout field (default 10s) is now applied to the http.Server created by these methods. Users can customize the value or use a custom http.Server for full control. Fixes #4760 Co-authored-by: Bo-Yi Wu --- gin.go | 39 ++++++++++++++++++++++++++++++++++----- gin_test.go | 20 ++++++++++++++++++++ 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/gin.go b/gin.go index 2e033bf3..a1607275 100644 --- a/gin.go +++ b/gin.go @@ -13,6 +13,7 @@ import ( "path" "strings" "sync" + "time" "github.com/gin-gonic/gin/internal/bytesconv" filesystem "github.com/gin-gonic/gin/internal/fs" @@ -29,6 +30,12 @@ const ( backslash = "\\" ) +// defaultReadHeaderTimeout is the default ReadHeaderTimeout applied to the +// http.Server created by Run, RunTLS and RunListener. It protects against +// slowloris-style resource exhaustion when the caller does not configure a +// custom http.Server. +const defaultReadHeaderTimeout = 10 * time.Second + var ( default404Body = []byte("404 page not found") default405Body = []byte("405 method not allowed") @@ -166,6 +173,12 @@ type Engine struct { // method call. MaxMultipartMemory int64 + // ReadHeaderTimeout is the maximum duration allowed for reading the request + // headers by the http.Server created through Run, RunTLS and RunListener. + // If zero or negative, a default of 10 seconds is used. Set to a positive + // value to customize, or use a custom http.Server directly to disable it. + ReadHeaderTimeout time.Duration + // UseH2C enable h2c support. UseH2C bool @@ -219,6 +232,7 @@ func New(opts ...OptionFunc) *Engine { RemoveExtraSlash: false, UnescapePathValues: true, MaxMultipartMemory: defaultMultipartMemory, + ReadHeaderTimeout: defaultReadHeaderTimeout, trees: make(methodTrees, 0, 9), delims: render.Delims{Left: "{{", Right: "}}"}, secureJSONPrefix: "while(1);", @@ -255,6 +269,15 @@ func (engine *Engine) allocateContext(maxParams uint16) *Context { return &Context{engine: engine, params: &v, skippedNodes: &skippedNodes} } +// getReadHeaderTimeout returns the configured ReadHeaderTimeout, or the +// default if it is zero or negative. +func (engine *Engine) getReadHeaderTimeout() time.Duration { + if engine.ReadHeaderTimeout <= 0 { + return defaultReadHeaderTimeout + } + return engine.ReadHeaderTimeout +} + // Delims sets template left and right delims and returns an Engine instance. func (engine *Engine) Delims(left, right string) *Engine { engine.delims = render.Delims{Left: left, Right: right} @@ -537,6 +560,9 @@ func parseIP(ip string) net.IP { // Run attaches the router to a http.Server and starts listening and serving HTTP requests. // It is a shortcut for http.ListenAndServe(addr, router) // Note: this method will block the calling goroutine indefinitely unless an error happens. +// The created http.Server is configured with a default ReadHeaderTimeout of 10 seconds +// (configurable via Engine.ReadHeaderTimeout) to mitigate slowloris attacks. +// For full control over timeouts, create a custom http.Server and use ServeHTTP. func (engine *Engine) Run(addr ...string) (err error) { defer func() { debugPrintError(err) }() @@ -548,8 +574,9 @@ func (engine *Engine) Run(addr ...string) (err error) { address := resolveAddress(addr) debugPrint("Listening and serving HTTP on %s\n", address) server := &http.Server{ // #nosec G112 - Addr: address, - Handler: engine.Handler(), + Addr: address, + Handler: engine.Handler(), + ReadHeaderTimeout: engine.getReadHeaderTimeout(), } err = server.ListenAndServe() return @@ -568,8 +595,9 @@ func (engine *Engine) RunTLS(addr, certFile, keyFile string) (err error) { } server := &http.Server{ // #nosec G112 - Addr: addr, - Handler: engine.Handler(), + Addr: addr, + Handler: engine.Handler(), + ReadHeaderTimeout: engine.getReadHeaderTimeout(), } err = server.ListenAndServeTLS(certFile, keyFile) return @@ -652,7 +680,8 @@ func (engine *Engine) RunListener(listener net.Listener) (err error) { } server := &http.Server{ // #nosec G112 - Handler: engine.Handler(), + Handler: engine.Handler(), + ReadHeaderTimeout: engine.getReadHeaderTimeout(), } err = server.Serve(listener) return diff --git a/gin_test.go b/gin_test.go index b488c446..71a817a7 100644 --- a/gin_test.go +++ b/gin_test.go @@ -1024,6 +1024,26 @@ func TestWithOptionFunc(t *testing.T) { assertRoutePresent(t, routes, RouteInfo{Path: "/test2", Method: http.MethodGet, Handler: "github.com/gin-gonic/gin.handlerTest2"}) } +func TestReadHeaderTimeoutDefault(t *testing.T) { + engine := New() + assert.Equal(t, defaultReadHeaderTimeout, engine.ReadHeaderTimeout) + assert.Equal(t, defaultReadHeaderTimeout, engine.getReadHeaderTimeout()) +} + +func TestReadHeaderTimeoutCustom(t *testing.T) { + engine := New(func(e *Engine) { + e.ReadHeaderTimeout = 30 * time.Second + }) + assert.Equal(t, 30*time.Second, engine.ReadHeaderTimeout) + assert.Equal(t, 30*time.Second, engine.getReadHeaderTimeout()) +} + +func TestReadHeaderTimeoutZeroFallsBackToDefault(t *testing.T) { + engine := New() + engine.ReadHeaderTimeout = 0 + assert.Equal(t, defaultReadHeaderTimeout, engine.getReadHeaderTimeout()) +} + type Birthday string func (b *Birthday) UnmarshalParam(param string) error { From 3b08cd7235bd5ad2f055aa9e38135f111f6c5926 Mon Sep 17 00:00:00 2001 From: water <672684719@qq.com> Date: Sat, 19 Sep 2026 21:11:32 +0800 Subject: [PATCH 22/27] fix: reset skipped-nodes stack on getValue entry to prevent slice overflow panic [#4818] (#4819) * fix: reset skipped-nodes stack on getValue entry to prevent slice overflow panic [#4818] * test: add regression test for getValue skipped-nodes overflow panic [#4818] * test(gin): consolidate routing regression tests - Move skipped-node regression cases into the existing routing test suite without changing behavior. --------- Co-authored-by: Bo-Yi Wu --- routes_test.go | 97 ++++++++++++++++++++++++++++++++++++++++++++++++++ tree.go | 8 +++++ 2 files changed, 105 insertions(+) diff --git a/routes_test.go b/routes_test.go index e9a89252..dbfaad5c 100644 --- a/routes_test.go +++ b/routes_test.go @@ -844,3 +844,100 @@ func TestEngineHandleMethodNotAllowedCornerCase(t *testing.T) { w := PerformRequest(r, http.MethodGet, "/base/v1/user/groups") assert.Equal(t, http.StatusNotFound, w.Code) } + +// TestIssue4818_skippedNodesOverflow_Panic reproduces the panic from issue #4818: +// with HandleMethodNotAllowed enabled, getValue is called once per method tree +// reusing the same c.skippedNodes stack without resetting it, so residue +// accumulates until the reslice exceeds the capacity (engine.maxSections). +// The request must not panic and must fall through to the normal 404 path +// (the path genuinely matches no route, so 405 is not applicable here). +func TestIssue4818_skippedNodesOverflow_Panic(t *testing.T) { + router := New() + router.HandleMethodNotAllowed = true + + h := func(c *Context) {} + router.OPTIONS("/:p0/:p1/a/:p2", h) + router.GET("/:p0/:p1/a/:p2", h) + router.PATCH("/b/:p0/:p1/c", h) + router.DELETE("/b/:p0/:p1/d/:p3", h) + router.GET("/b/:p0/:p1/e/f", h) + router.POST("/b/:p0/:p1/g/:p4/h", h) + router.OPTIONS("/b/:p0/:p1/g/:p4/h", h) + router.DELETE("/b/cache", h) + router.GET("/b/clients/:p1/g", h) + router.POST("/b/clients/:p1/g", h) + router.PATCH("/b/clients/:p1/g/:p4", h) + router.OPTIONS("/b/clients/:p1/g/:p4", h) + + req := httptest.NewRequest(http.MethodPost, "/b/clients/42", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + // Must not panic; path matches no route, so 404 is the correct outcome. + if w.Code != http.StatusNotFound { + t.Fatalf("expected 404, got %d (a panic would have aborted the test)", w.Code) + } +} + +// TestIssue4818_MethodNotAllowedStillWorks verifies the HandleMethodNotAllowed +// loop still produces a correct 405 with an Allow header after the fix, i.e. +// the reset does not break the loop across multiple method trees. +func TestIssue4818_MethodNotAllowedStillWorks(t *testing.T) { + router := New() + router.HandleMethodNotAllowed = true + + h := func(c *Context) {} + router.OPTIONS("/:p0/:p1/a/:p2", h) + router.GET("/:p0/:p1/a/:p2", h) + router.PATCH("/b/:p0/:p1/c", h) + router.DELETE("/b/:p0/:p1/d/:p3", h) + router.GET("/b/:p0/:p1/e/f", h) + router.POST("/b/:p0/:p1/g/:p4/h", h) + router.OPTIONS("/b/:p0/:p1/g/:p4/h", h) + router.DELETE("/b/cache", h) + router.GET("/b/clients/:p1/g", h) + router.POST("/b/clients/:p1/g", h) + router.PATCH("/b/clients/:p1/g/:p4", h) + router.OPTIONS("/b/clients/:p1/g/:p4", h) + + // PATCH /b/clients/42/g is registered under GET but not under PATCH + // -> HandleMethodNotAllowed should yield 405 with an Allow header. + req := httptest.NewRequest(http.MethodPatch, "/b/clients/42/g", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + if w.Code != http.StatusMethodNotAllowed { + t.Fatalf("expected 405, got %d", w.Code) + } + allow := w.Header().Get("Allow") + if allow == "" { + t.Fatal("expected Allow header to be set for 405") + } +} + +// TestIssue4818_MethodNotAllowedManyTrees stresses the loop across many +// method trees to make sure the skipped-nodes accumulator can never overflow. +func TestIssue4818_MethodNotAllowedManyTrees(t *testing.T) { + router := New() + router.HandleMethodNotAllowed = true + + h := func(c *Context) {} + for _, m := range []string{ + http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, + http.MethodPatch, http.MethodOptions, http.MethodHead, http.MethodConnect, + http.MethodTrace, + } { + router.Handle(m, "/:p0/:p1/a/:p2", h) + router.Handle(m, "/s/:p0/:p1/:p2/:p3/:p4/:p5/d", h) + } + // GET route so that a POST to a GET-only path yields 405 + router.GET("/only-get", h) + + req := httptest.NewRequest(http.MethodPost, "/only-get", nil) + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + if w.Code != http.StatusMethodNotAllowed { + t.Fatalf("expected 405, got %d", w.Code) + } +} diff --git a/tree.go b/tree.go index dc84ff61..6efe2e0e 100644 --- a/tree.go +++ b/tree.go @@ -418,6 +418,14 @@ type skippedNode struct { func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode, unescape bool) (value nodeValue) { var globalParamsCount int16 + // Reset the skipped-nodes stack on entry. getValue is called once per + // method tree (e.g. in the HandleMethodNotAllowed loop) reusing the same + // pooled Context stack, and the walk below grows it via a raw reslice that + // cannot exceed engine.maxSections. Without this reset the residue from a + // previous tree leaks into the next call and can panic with "slice bounds + // out of range" once the accumulated length passes the capacity. + *skippedNodes = (*skippedNodes)[:0] + walk: // Outer loop for walking the tree for { prefix := n.path From 1bd0ecf2d3e08da37efa270bb7be20c1eddb0d68 Mon Sep 17 00:00:00 2001 From: HazyLab Date: Fri, 25 Sep 2026 08:01:37 +0200 Subject: [PATCH 23/27] fix(context): load Keys under the mutex in Copy (#4854) Copy read c.Keys before RLock. Set stores that field under Lock when the map is created. The race detector reports the unsynchronized access, and the copy can observe a nil header and drop keys Set has already published. maps.Clone(nil) returns nil, so the load and the clone belong in the same critical section. Map iteration was already under the mutex. Co-authored-by: hazyhaar --- context.go | 3 +-- context_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/context.go b/context.go index 788b00bb..a6add8a6 100644 --- a/context.go +++ b/context.go @@ -132,9 +132,8 @@ func (c *Context) Copy() *Context { cp.handlers = nil cp.fullPath = c.fullPath - cKeys := c.Keys c.mu.RLock() - cp.Keys = maps.Clone(cKeys) + cp.Keys = maps.Clone(c.Keys) c.mu.RUnlock() cParams := c.Params diff --git a/context_test.go b/context_test.go index cef488c9..b82e04d5 100644 --- a/context_test.go +++ b/context_test.go @@ -709,6 +709,30 @@ func TestContextGetStringMapStringSlice(t *testing.T) { assert.Equal(t, []string{"foo"}, c.GetStringMapStringSlice("map")["foo"]) } +func TestCopyConcurrentWithSet(t *testing.T) { + c := &Context{} + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + for i := 0; i < 100; i++ { + c.Set(i, i) + } + }() + go func() { + defer wg.Done() + for i := 0; i < 100; i++ { + cp := c.Copy() + for k, v := range cp.Keys { + if k != v { + t.Errorf("copied key %v = %v, want %v", k, v, k) + } + } + } + }() + wg.Wait() +} + func TestContextCopy(t *testing.T) { c, _ := CreateTestContext(httptest.NewRecorder()) c.index = 2 From 43fe48e8a0f44af783116cdb010725e6bb50255f Mon Sep 17 00:00:00 2001 From: Zain Qureshi <43629888+ZainnQureshii@users.noreply.github.com> Date: Tue, 29 Sep 2026 15:14:45 +0200 Subject: [PATCH 24/27] docs: fix SecureJSON default prefix and default-binding example output (#4861) The SecureJSON docs and the Context.SecureJSON comment said the default prefix is "while(1),". The engine sets secureJSONPrefix to "while(1);" (gin.go), and the example output a few lines below already shows the semicolon. The default-values binding example printed a "Colors" field that the Person struct does not have; the struct's array field is Addresses with default "foo bar", which binds to ["foo","bar"]. Co-authored-by: Claude Opus 5.5 --- context.go | 2 +- docs/doc.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/context.go b/context.go index a6add8a6..582d00f2 100644 --- a/context.go +++ b/context.go @@ -1236,7 +1236,7 @@ func (c *Context) IndentedJSON(code int, obj any) { } // SecureJSON serializes the given struct as Secure JSON into the response body. -// Default prepends "while(1)," to response body if the given struct is array values. +// Default prepends "while(1);" to response body if the given struct is array values. // It also sets the Content-Type as "application/json". func (c *Context) SecureJSON(code int, obj any) { c.Render(code, render.SecureJSON{Prefix: c.engine.secureJSONPrefix, Data: obj}) diff --git a/docs/doc.md b/docs/doc.md index 3f0c94ea..16102841 100644 --- a/docs/doc.md +++ b/docs/doc.md @@ -1167,7 +1167,7 @@ func main() { ```sh curl -X POST http://localhost:8080/person -{"Name":"William","Age":10,"Friends":["Will","Bill"],"Colors":["red","blue"],"LapTimes":[1,2,3]} +{"Name":"William","Age":10,"Friends":["Will","Bill"],"Addresses":["foo","bar"],"LapTimes":[1,2,3]} ``` NOTE: For default [collection values](#collection-format-for-arrays), the following rules apply: @@ -1762,7 +1762,7 @@ func main() { #### SecureJSON -Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values. +Using SecureJSON to prevent json hijacking. Default prepends `"while(1);"` to response body if the given struct is array values. ```go func main() { From e8f24969d59611428b03d02424b8f4bb55a1ef91 Mon Sep 17 00:00:00 2001 From: adam magued Date: Sat, 10 Oct 2026 07:16:17 +0300 Subject: [PATCH 25/27] feat(routergroup): include HTTP QUERY method in Any (#4878) Signed-off-by: AdamMagued --- docs/doc.md | 3 +-- routergroup.go | 8 ++------ routergroup_test.go | 22 ++++++++++++++++++++++ routes_test.go | 10 ++++++---- 4 files changed, 31 insertions(+), 12 deletions(-) diff --git a/docs/doc.md b/docs/doc.md index 16102841..366b249b 100644 --- a/docs/doc.md +++ b/docs/doc.md @@ -167,9 +167,8 @@ Use the `gin.MethodQuery` constant wherever an HTTP method name is expected, for req := httptest.NewRequest(gin.MethodQuery, "/search", body) ``` -Two things to keep in mind: +Keep in mind: -- `router.Any` does not register `QUERY`, so existing catch-all routes keep matching exactly the methods they matched before. Use `router.QUERY` or `router.Match([]string{gin.MethodQuery, http.MethodPost}, ...)` when you want it. - `QUERY` is not part of the `gin.IRoutes` interface. `*gin.Engine` and `*gin.RouterGroup` expose it directly; if you only hold an `IRoutes` value, assert to `gin.IQueryRoutes` first. ```go diff --git a/routergroup.go b/routergroup.go index d85a8baf..47eeee58 100644 --- a/routergroup.go +++ b/routergroup.go @@ -24,7 +24,7 @@ var ( anyMethods = []string{ http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodHead, http.MethodOptions, http.MethodDelete, http.MethodConnect, - http.MethodTrace, + http.MethodTrace, MethodQuery, } ) @@ -178,11 +178,7 @@ func (group *RouterGroup) QUERY(relativePath string, handlers ...HandlerFunc) IR } // Any registers a route that matches all the HTTP methods. -// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE. -// -// QUERY is not part of that list, so that Any keeps registering exactly the -// same routes as before. Register it with QUERY, or with -// Match([]string{gin.MethodQuery, ...}, ...) to combine it with other methods. +// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE, QUERY. func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes { for _, method := range anyMethods { group.handle(method, relativePath, handlers) diff --git a/routergroup_test.go b/routergroup_test.go index be5c7819..c3859a35 100644 --- a/routergroup_test.go +++ b/routergroup_test.go @@ -221,3 +221,25 @@ func TestRouterGroupCombineHandlersEmptySliceNotNil(t *testing.T) { assert.NotNil(t, result, "result should not be nil even with empty handlers") assert.Empty(t, result, "empty handlers should return empty chain") } + +func TestRouterGroupAny(t *testing.T) { + router := New() + router.Any("/any", func(c *Context) { + c.String(http.StatusOK, c.Request.Method) + }) + + v1 := router.Group("/v1") + v1.Any("/any", func(c *Context) { + c.String(http.StatusOK, "v1:"+c.Request.Method) + }) + + for _, method := range anyMethods { + w := PerformRequest(router, method, "/any") + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, method, w.Body.String()) + + w = PerformRequest(router, method, "/v1/any") + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "v1:"+method, w.Body.String()) + } +} diff --git a/routes_test.go b/routes_test.go index dbfaad5c..3306233f 100644 --- a/routes_test.go +++ b/routes_test.go @@ -110,9 +110,8 @@ func TestRouteQuery(t *testing.T) { assert.Equal(t, "gin", w.Body.String()) } -// TestRouteQueryNotRegisteredByAny documents that Any does not register QUERY, -// so that existing Any routes keep matching exactly the methods they used to. -func TestRouteQueryNotRegisteredByAny(t *testing.T) { +// TestRouteQueryRegisteredByAny documents that Any registers QUERY. +func TestRouteQueryRegisteredByAny(t *testing.T) { router := New() router.Any("/test", func(c *Context) { c.Status(http.StatusOK) @@ -120,7 +119,7 @@ func TestRouteQueryNotRegisteredByAny(t *testing.T) { w := PerformRequest(router, MethodQuery, "/test") - assert.Equal(t, http.StatusNotFound, w.Code) + assert.Equal(t, http.StatusOK, w.Code) } // TestQueryRoutesInterface tests that a router reached through IRoutes can @@ -171,6 +170,7 @@ func TestRouterGroupRouteOK(t *testing.T) { testRouteOK(http.MethodDelete, t) testRouteOK(http.MethodConnect, t) testRouteOK(http.MethodTrace, t) + testRouteOK(MethodQuery, t) } func TestRouteNotOK(t *testing.T) { @@ -183,6 +183,7 @@ func TestRouteNotOK(t *testing.T) { testRouteNotOK(http.MethodDelete, t) testRouteNotOK(http.MethodConnect, t) testRouteNotOK(http.MethodTrace, t) + testRouteNotOK(MethodQuery, t) } func TestRouteNotOK2(t *testing.T) { @@ -195,6 +196,7 @@ func TestRouteNotOK2(t *testing.T) { testRouteNotOK2(http.MethodDelete, t) testRouteNotOK2(http.MethodConnect, t) testRouteNotOK2(http.MethodTrace, t) + testRouteNotOK2(MethodQuery, t) } func TestRouteRedirectTrailingSlash(t *testing.T) { From ea9fab99e01d55a5e4f8daacc0d11ccffaee0a15 Mon Sep 17 00:00:00 2001 From: HazyLab Date: Sat, 10 Oct 2026 06:18:54 +0200 Subject: [PATCH 26/27] fix(tree): grow skippedNodes when pooled capacity is stale (#4852) getValue resliced the backtrack stack to index+1 on the assumption that its capacity equals Engine.maxSections. The pool captures that capacity at allocation. Routes registered afterwards raise maxSections without resizing the pooled slice. The next request that needs one more frame panics inside the router, before Recovery. append grows the slice when the captured capacity is short and preserves the existing backtrack behaviour when it is already sufficient. The reset at entry stays: getValue still runs once per method tree on the same stack. Co-authored-by: hazyhaar Co-authored-by: Bo-Yi Wu --- routes_test.go | 24 ++++++++++++++++++++++++ tree.go | 15 +++++++-------- 2 files changed, 31 insertions(+), 8 deletions(-) diff --git a/routes_test.go b/routes_test.go index 3306233f..a032a2b7 100644 --- a/routes_test.go +++ b/routes_test.go @@ -847,6 +847,30 @@ func TestEngineHandleMethodNotAllowedCornerCase(t *testing.T) { assert.Equal(t, http.StatusNotFound, w.Code) } +func TestLateRouteRegistrationSkippedNodes(t *testing.T) { + router := New() + router.HandleMethodNotAllowed = true + router.GET("/a", func(c *Context) { c.Status(http.StatusOK) }) + + w := PerformRequest(router, http.MethodGet, "/a") + if w.Code != http.StatusOK { + t.Fatalf("warmup status = %d, want 200", w.Code) + } + + h := func(c *Context) {} + router.GET("/x/y/z/w", h) + router.GET("/x/y/:id/w", h) + router.GET("/x/:id/z/w", h) + router.GET("/:id/y/z/w", h) + + req := httptest.NewRequest(http.MethodPost, "/x/y/z/w/extra", nil) + w = httptest.NewRecorder() + router.ServeHTTP(w, req) + if w.Code != http.StatusNotFound { + t.Fatalf("status = %d, want 404", w.Code) + } +} + // TestIssue4818_skippedNodesOverflow_Panic reproduces the panic from issue #4818: // with HandleMethodNotAllowed enabled, getValue is called once per method tree // reusing the same c.skippedNodes stack without resetting it, so residue diff --git a/tree.go b/tree.go index 6efe2e0e..6842d225 100644 --- a/tree.go +++ b/tree.go @@ -420,10 +420,11 @@ func (n *node) getValue(path string, params *Params, skippedNodes *[]skippedNode // Reset the skipped-nodes stack on entry. getValue is called once per // method tree (e.g. in the HandleMethodNotAllowed loop) reusing the same - // pooled Context stack, and the walk below grows it via a raw reslice that - // cannot exceed engine.maxSections. Without this reset the residue from a - // previous tree leaks into the next call and can panic with "slice bounds - // out of range" once the accumulated length passes the capacity. + // pooled Context stack. Without this reset the residue from a previous + // tree leaks into the next call. The walk grows the stack with append: + // a context allocated before addRoute raised maxSections must still be + // able to record one more backtrack frame. A raw reslice of the capacity + // captured at pool allocation panics with "slice bounds out of range". *skippedNodes = (*skippedNodes)[:0] walk: // Outer loop for walking the tree @@ -439,9 +440,7 @@ walk: // Outer loop for walking the tree if c == idxc { // strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild if n.wildChild { - index := len(*skippedNodes) - *skippedNodes = (*skippedNodes)[:index+1] - (*skippedNodes)[index] = skippedNode{ + *skippedNodes = append(*skippedNodes, skippedNode{ path: prefix + path, node: &node{ path: n.path, @@ -453,7 +452,7 @@ walk: // Outer loop for walking the tree fullPath: n.fullPath, }, paramsCount: globalParamsCount, - } + }) } n = n.children[i] From 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646 Mon Sep 17 00:00:00 2001 From: Little Fedya Date: Sat, 10 Oct 2026 09:20:35 +0500 Subject: [PATCH 27/27] docs: include HTTP QUERY method in RouterGroup.Any (#4879) Co-authored-by: Bo-Yi Wu --- docs/doc.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/doc.md b/docs/doc.md index 366b249b..01edf52c 100644 --- a/docs/doc.md +++ b/docs/doc.md @@ -169,6 +169,7 @@ req := httptest.NewRequest(gin.MethodQuery, "/search", body) Keep in mind: +- `router.Any` also registers `QUERY` alongside standard HTTP methods. Handlers registered with `Any` should respect QUERY's safe and idempotent semantics when processing that method. - `QUERY` is not part of the `gin.IRoutes` interface. `*gin.Engine` and `*gin.RouterGroup` expose it directly; if you only hold an `IRoutes` value, assert to `gin.IQueryRoutes` first. ```go