Merge 61b357bbf1eee645bab5483bd2be913a88342075 into 5c6a15f8f9566612076bd209e623861bf92a6283

This commit is contained in:
Gaurav Patil 2026-09-17 17:33:29 +09:00 committed by GitHub
commit e164781f51
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 156 additions and 1 deletions

View File

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

View File

@ -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...)

View File

@ -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")

View File

@ -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 {
@ -119,6 +143,15 @@ func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRou
return group.handle(http.MethodGet, relativePath, handlers)
}
// QUERY is a shortcut for router.Handle("QUERY", path, handlers).
//
// 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(MethodQuery, relativePath, handlers)
}
// DELETE is a shortcut for router.Handle("DELETE", path, handlers).
func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes {
return group.handle(http.MethodDelete, relativePath, handlers)
@ -153,6 +186,10 @@ 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.
func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
for _, method := range anyMethods {
group.handle(method, relativePath, handlers)

View File

@ -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")
}

View File

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