mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-27 22:23:43 +08:00
Compare commits
6 Commits
ee0e81fcff
...
73c2f26b20
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
73c2f26b20 | ||
|
|
0f09c3a9b4 | ||
|
|
ea9fab99e0 | ||
|
|
e8f24969d5 | ||
|
|
3f607b8662 | ||
|
|
4a0302068c |
@ -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
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -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())
|
||||
}
|
||||
}
|
||||
|
||||
@ -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
|
||||
|
||||
@ -34,6 +34,30 @@ func CreateTestContextOnly(w http.ResponseWriter, r *Engine) (c *Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// RunTestHandler creates a test context, assigns the given request, executes
|
||||
// the provided handler chain, and flushes the status code to the underlying
|
||||
// ResponseWriter. This solves the problem where ctx.Status() sets the status
|
||||
// internally but does not flush it to an httptest.ResponseRecorder when using
|
||||
// CreateTestContext directly.
|
||||
//
|
||||
// Example usage:
|
||||
//
|
||||
// w := httptest.NewRecorder()
|
||||
// req := httptest.NewRequest("POST", "/resource", nil)
|
||||
// c := gin.RunTestHandler(w, req, func(c *gin.Context) {
|
||||
// c.Status(http.StatusCreated)
|
||||
// })
|
||||
// // w.Code is now 201, not 200
|
||||
func RunTestHandler(w http.ResponseWriter, req *http.Request, handlers ...HandlerFunc) *Context {
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Request = req
|
||||
c.handlers = handlers
|
||||
c.index = -1
|
||||
c.Next()
|
||||
c.Writer.WriteHeaderNow()
|
||||
return c
|
||||
}
|
||||
|
||||
// waitForServerReady waits for a server to be ready by making HTTP requests
|
||||
// with exponential backoff. This is more reliable than time.Sleep() for testing.
|
||||
func waitForServerReady(url string, maxAttempts int) error {
|
||||
|
||||
101
test_helpers_test.go
Normal file
101
test_helpers_test.go
Normal file
@ -0,0 +1,101 @@
|
||||
// Copyright 2017 Manu Martinez-Almeida. All rights reserved.
|
||||
// Use of this source code is governed by a MIT style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package gin
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestRunTestHandlerFlushesStatusCode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
statusCode int
|
||||
}{
|
||||
{"201 Created", http.StatusCreated},
|
||||
{"204 No Content", http.StatusNoContent},
|
||||
{"400 Bad Request", http.StatusBadRequest},
|
||||
{"404 Not Found", http.StatusNotFound},
|
||||
{"500 Internal Server Error", http.StatusInternalServerError},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
code := tt.statusCode
|
||||
|
||||
c := RunTestHandler(w, req, func(c *Context) {
|
||||
c.Status(code)
|
||||
})
|
||||
|
||||
assert.Equal(t, code, w.Code)
|
||||
assert.Equal(t, code, c.Writer.Status())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunTestHandlerMultipleHandlers(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPost, "/resource", nil)
|
||||
|
||||
callOrder := []string{}
|
||||
|
||||
middleware := func(c *Context) {
|
||||
callOrder = append(callOrder, "middleware")
|
||||
c.Next()
|
||||
}
|
||||
|
||||
handler := func(c *Context) {
|
||||
callOrder = append(callOrder, "handler")
|
||||
c.Status(http.StatusCreated)
|
||||
}
|
||||
|
||||
c := RunTestHandler(w, req, middleware, handler)
|
||||
|
||||
assert.Equal(t, http.StatusCreated, w.Code)
|
||||
assert.Equal(t, http.StatusCreated, c.Writer.Status())
|
||||
assert.Equal(t, []string{"middleware", "handler"}, callOrder)
|
||||
}
|
||||
|
||||
func TestRunTestHandlerDefaultStatus(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
|
||||
RunTestHandler(w, req, func(c *Context) {
|
||||
// Handler that does not set a status explicitly.
|
||||
})
|
||||
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
}
|
||||
|
||||
func TestRunTestHandlerSetsRequest(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPut, "/items/42", nil)
|
||||
|
||||
c := RunTestHandler(w, req, func(c *Context) {
|
||||
c.Status(http.StatusOK)
|
||||
})
|
||||
|
||||
assert.Equal(t, req, c.Request)
|
||||
}
|
||||
|
||||
func TestCreateTestContextBackwardCompatible(t *testing.T) {
|
||||
// Verify that CreateTestContext still behaves the same way:
|
||||
// status is stored internally but NOT flushed to the ResponseRecorder.
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
c.Status(http.StatusCreated)
|
||||
|
||||
// The internal status should be set.
|
||||
assert.Equal(t, http.StatusCreated, c.Writer.Status())
|
||||
|
||||
// But w.Code should still be the default 200 because WriteHeaderNow
|
||||
// was never called. This confirms backward compatibility.
|
||||
assert.Equal(t, http.StatusOK, w.Code)
|
||||
}
|
||||
15
tree.go
15
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]
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user