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) {