Skip to content
Myr

feat(gin): add support for the HTTP QUERY method (RFC 10008) (#4806)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* 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 ---------

authored by Gaurav Patil · committed by GitHub · parent 05b14df · Browse files · 6 files+152 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
  • Co-authored-by: Bo-Yi Wu <appleboy.tw@gmail.com>

Diff stats

6 files+152 added−4 removed

  • other:+152 added−4 removed

6 files+152 added−4 removed

modified:docs/doc.md+41 added
5 unmodified lines
6 - [Build with json replacement](#build-with-json-replacement)7 - [Build without MsgPack rendering feature](#build-without-msgpack-rendering-feature)8- [Routing](#routing)9 - [Using GET, POST, PUT, PATCH, DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options)10 - [Using the QUERY method](#using-the-query-method)11 - [Parameters in path](#parameters-in-path)12 - [Querystring parameters](#querystring-parameters)13 - [Multipart/Urlencoded Form](#multiparturlencoded-form)14 - [Another example: query + post form](#another-example-query--post-form)
122 unmodified lines
137 // router.Run(":3000") for a hard coded port138}139```140141### Using the QUERY method142143`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`.144145```go146func main() {147 router := gin.Default()148149 router.QUERY("/search", func(c *gin.Context) {150 var query struct {151 Term string `json:"term"`152 }153 if err := c.ShouldBindJSON(&query); err != nil {154 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})155 return156 }157 c.JSON(http.StatusOK, gin.H{"term": query.Term})158 })159160 router.Run()161}162```163164Use the `gin.MethodQuery` constant wherever an HTTP method name is expected, for example when building a request in a test:165166```go167req := httptest.NewRequest(gin.MethodQuery, "/search", body)168```169170Two things to keep in mind:171172- `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.173- `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.174175```go176if q, ok := routes.(gin.IQueryRoutes); ok {177 q.QUERY("/search", searching)178}179```180181### Parameters in path182183```go184func main() {
2523 unmodified lines
modified:ginS/gins_test.go+13 added
29 unmodified lines
30 assert.Equal(t, http.StatusOK, w.Code)31 assert.Equal(t, "test", w.Body.String())32}3334func TestQUERY(t *testing.T) {35 QUERY("/query", func(c *gin.Context) {36 c.String(http.StatusOK, "query")37 })3839 req := httptest.NewRequest(gin.MethodQuery, "/query", nil)40 w := httptest.NewRecorder()41 engine().ServeHTTP(w, req)4243 assert.Equal(t, http.StatusOK, w.Code)44 assert.Equal(t, "query", w.Body.String())45}4647func TestPOST(t *testing.T) {48 POST("/post", func(c *gin.Context) {49 c.String(http.StatusCreated, "created")50 })
209 unmodified lines
modified:ginS/gins.go+5 added
65 unmodified lines
66func GET(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {67 return engine().GET(relativePath, handlers...)68}6970// QUERY is a shortcut for router.Handle("QUERY", path, handle)71func QUERY(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {72 return engine().QUERY(relativePath, handlers...)73}7475// DELETE is a shortcut for router.Handle("DELETE", path, handle)76func DELETE(relativePath string, handlers ...gin.HandlerFunc) gin.IRoutes {77 return engine().DELETE(relativePath, handlers...)78}
86 unmodified lines
modified:routergroup_test.go+4 added
40 unmodified lines
41 performRequestInGroup(t, http.MethodPatch)42 performRequestInGroup(t, http.MethodDelete)43 performRequestInGroup(t, http.MethodHead)44 performRequestInGroup(t, http.MethodOptions)45 performRequestInGroup(t, MethodQuery)46}4748func performRequestInGroup(t *testing.T, method string) {49 router := New()
28 unmodified lines
78 login.HEAD("/test", handler)79 case http.MethodOptions:80 v1.OPTIONS("/test", handler)81 login.OPTIONS("/test", handler)82 case MethodQuery:83 v1.QUERY("/test", handler)84 login.QUERY("/test", handler)85 default:86 panic("unknown method")87 }88
135 unmodified lines
modified:routergroup.go+34 added-4 removed
9 unmodified lines
10 "regexp"11 "strings"12)1314// MethodQuery is the HTTP QUERY method defined by RFC 10008. It is declared15// here because the standard library does not provide http.MethodQuery yet.16// Once it does, this constant keeps the same value and stays valid.17const MethodQuery = "QUERY"1819var (20 // regEnLetter matches english letters for http method name21 regEnLetter = regexp.MustCompile("^[A-Z]+$")22
31 unmodified lines
54 Static(string, string) IRoutes55 StaticFS(string, http.FileSystem) IRoutes56}5758// IQueryRoutes defines the router handle interface for the HTTP QUERY method.59//60// It is deliberately kept out of IRoutes: adding a method to IRoutes would61// break every type outside of Gin that implements it, such as test doubles and62// wrappers. Type assert when you only hold an IRoutes value:63//64// if q, ok := routes.(gin.IQueryRoutes); ok {65// q.QUERY("/search", handler)66// }67//68// *gin.RouterGroup and *gin.Engine satisfy this interface, so the assertion is69// only needed when the concrete type has been erased.70type IQueryRoutes interface {71 QUERY(string, ...HandlerFunc) IRoutes72}7374// RouterGroup is used internally to configure router, a RouterGroup is associated with75// a prefix and an array of handlers (middleware).76type RouterGroup struct {77 Handlers HandlersChain
1 unmodified line
79 engine *Engine80 root bool81}8283var (62var _ IRouter = (*RouterGroup)(nil)84 _ IRouter = (*RouterGroup)(nil)85 _ IQueryRoutes = (*RouterGroup)(nil)86)8788// Use adds middleware to the group, see example code in GitHub.89func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {90 group.Handlers = append(group.Handlers, middleware...)
77 unmodified lines
168 return group.handle(http.MethodHead, relativePath, handlers)169}170171// QUERY is a shortcut for router.Handle("QUERY", path, handlers).148// The QUERY method is defined by RFC 10008 and is used to send a query149// in the request body, similar to GET but with a body.172//173// QUERY is the safe and idempotent method defined by RFC 10008 that carries its174// query in the request body. The body is read like any other body, for example175// with c.ShouldBindJSON.176func (group *RouterGroup) QUERY(relativePath string, handlers ...HandlerFunc) IRoutes {151 return group.handle("QUERY", relativePath, handlers)177 return group.handle(MethodQuery, relativePath, handlers)178}179180// Any registers a route that matches all the HTTP methods.181// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.182//183// QUERY is not part of that list, so that Any keeps registering exactly the184// same routes as before. Register it with QUERY, or with185// Match([]string{gin.MethodQuery, ...}, ...) to combine it with other methods.186func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {187 for _, method := range anyMethods {188 group.handle(method, relativePath, handlers)189 }
110 unmodified lines
modified:routes_test.go+55 added
8 unmodified lines
9 "net/http"10 "net/http/httptest"11 "os"12 "path/filepath"13 "strings"14 "testing"1516 "github.com/stretchr/testify/assert"17 "github.com/stretchr/testify/require"
68 unmodified lines
86 assert.False(t, passed)87 assert.Equal(t, http.StatusMethodNotAllowed, w.Code)88}8990// TestRouteQuery tests that a QUERY route is invoked and can read the request91// body, which is the whole point of the method (RFC 10008).92func TestRouteQuery(t *testing.T) {93 type search struct {94 Term string `json:"term"`95 }9697 router := New()98 router.QUERY("/search", func(c *Context) {99 var body search100 require.NoError(t, c.ShouldBindJSON(&body))101 c.String(http.StatusOK, body.Term)102 })103104 req := httptest.NewRequest(MethodQuery, "/search", strings.NewReader(`{"term":"gin"}`))105 req.Header.Set("Content-Type", MIMEJSON)106 w := httptest.NewRecorder()107 router.ServeHTTP(w, req)108109 assert.Equal(t, http.StatusOK, w.Code)110 assert.Equal(t, "gin", w.Body.String())111}112113// TestRouteQueryNotRegisteredByAny documents that Any does not register QUERY,114// so that existing Any routes keep matching exactly the methods they used to.115func TestRouteQueryNotRegisteredByAny(t *testing.T) {116 router := New()117 router.Any("/test", func(c *Context) {118 c.Status(http.StatusOK)119 })120121 w := PerformRequest(router, MethodQuery, "/test")122123 assert.Equal(t, http.StatusNotFound, w.Code)124}125126// TestQueryRoutesInterface tests that a router reached through IRoutes can127// still register a QUERY route via the IQueryRoutes assertion.128func TestQueryRoutesInterface(t *testing.T) {129 router := New()130131 var routes IRoutes = router.Group("/v1")132 queryRoutes, ok := routes.(IQueryRoutes)133 require.True(t, ok)134135 queryRoutes.QUERY("/search", func(c *Context) {136 c.Status(http.StatusOK)137 })138139 w := PerformRequest(router, MethodQuery, "/v1/search")140141 assert.Equal(t, http.StatusOK, w.Code)142}143144func TestRouterMethod(t *testing.T) {145 router := New()146 router.PUT("/hey2", func(c *Context) {147 c.String(http.StatusOK, "sup2")
699 unmodified lines