diff --git a/context.go b/context.go index d27c6d49..06f645a8 100644 --- a/context.go +++ b/context.go @@ -1248,7 +1248,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..01edf52c 100644 --- a/docs/doc.md +++ b/docs/doc.md @@ -167,9 +167,9 @@ 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. +- `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 @@ -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() { 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..a032a2b7 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) { @@ -845,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]