mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-21 01:43:38 +08:00
Merge 6c406e98c98baf349cbd2b0588ae9c5874eaa4d2 into 0f09c3a9b4626d9fe9979cf4d0521d6ae32ab646
This commit is contained in:
commit
a6c77afb07
@ -75,6 +75,7 @@ var Validator StructValidator = &defaultValidator{}
|
||||
// present in the request to struct instances.
|
||||
var (
|
||||
JSON BindingBody = jsonBinding{}
|
||||
StrictJSON BindingBody = strictJSONBinding{}
|
||||
XML BindingBody = xmlBinding{}
|
||||
Form Binding = formBinding{}
|
||||
Query Binding = queryBinding{}
|
||||
|
||||
@ -72,6 +72,7 @@ var Validator StructValidator = &defaultValidator{}
|
||||
// present in the request to struct instances.
|
||||
var (
|
||||
JSON = jsonBinding{}
|
||||
StrictJSON = strictJSONBinding{}
|
||||
XML = xmlBinding{}
|
||||
Form = formBinding{}
|
||||
Query = queryBinding{}
|
||||
|
||||
@ -34,19 +34,38 @@ func (jsonBinding) Bind(req *http.Request, obj any) error {
|
||||
if req == nil || req.Body == nil {
|
||||
return errors.New("invalid request")
|
||||
}
|
||||
return decodeJSON(req.Body, obj)
|
||||
return decodeJSON(req.Body, obj, false)
|
||||
}
|
||||
|
||||
func (jsonBinding) BindBody(body []byte, obj any) error {
|
||||
return decodeJSON(bytes.NewReader(body), obj)
|
||||
return decodeJSON(bytes.NewReader(body), obj, false)
|
||||
}
|
||||
|
||||
func decodeJSON(r io.Reader, obj any) error {
|
||||
// strictJSONBinding is a JSON binding which always rejects unknown fields,
|
||||
// regardless of the value of EnableDecoderDisallowUnknownFields.
|
||||
type strictJSONBinding struct{}
|
||||
|
||||
func (strictJSONBinding) Name() string {
|
||||
return "strict-json"
|
||||
}
|
||||
|
||||
func (strictJSONBinding) Bind(req *http.Request, obj any) error {
|
||||
if req == nil || req.Body == nil {
|
||||
return errors.New("invalid request")
|
||||
}
|
||||
return decodeJSON(req.Body, obj, true)
|
||||
}
|
||||
|
||||
func (strictJSONBinding) BindBody(body []byte, obj any) error {
|
||||
return decodeJSON(bytes.NewReader(body), obj, true)
|
||||
}
|
||||
|
||||
func decodeJSON(r io.Reader, obj any, strict bool) error {
|
||||
decoder := json.API.NewDecoder(r)
|
||||
if EnableDecoderUseNumber {
|
||||
decoder.UseNumber()
|
||||
}
|
||||
if EnableDecoderDisallowUnknownFields {
|
||||
if strict || EnableDecoderDisallowUnknownFields {
|
||||
decoder.DisallowUnknownFields()
|
||||
}
|
||||
if err := decoder.Decode(obj); err != nil {
|
||||
|
||||
@ -6,6 +6,7 @@ package binding
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
@ -37,6 +38,98 @@ func TestJSONBindingBindBodyMap(t *testing.T) {
|
||||
assert.Equal(t, "world", s["hello"])
|
||||
}
|
||||
|
||||
func TestStrictJSONBindingName(t *testing.T) {
|
||||
assert.Equal(t, "strict-json", StrictJSON.Name())
|
||||
}
|
||||
|
||||
func TestStrictJSONBindingBind(t *testing.T) {
|
||||
type fooStruct struct {
|
||||
Foo string `json:"foo" binding:"required"`
|
||||
}
|
||||
|
||||
s := fooStruct{}
|
||||
req := requestWithBody(http.MethodPost, "/", `{"foo": "FOO"}`)
|
||||
require.NoError(t, StrictJSON.Bind(req, &s))
|
||||
assert.Equal(t, "FOO", s.Foo)
|
||||
|
||||
s = fooStruct{}
|
||||
req = requestWithBody(http.MethodPost, "/", `{"foo": "FOO", "what": "this"}`)
|
||||
err := StrictJSON.Bind(req, &s)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "what")
|
||||
|
||||
// validation still runs
|
||||
s = fooStruct{}
|
||||
req = requestWithBody(http.MethodPost, "/", `{}`)
|
||||
require.Error(t, StrictJSON.Bind(req, &s))
|
||||
|
||||
require.Error(t, StrictJSON.Bind(nil, &s))
|
||||
}
|
||||
|
||||
func TestStrictJSONBindingBindBody(t *testing.T) {
|
||||
var s struct {
|
||||
Foo string `json:"foo"`
|
||||
Nested struct {
|
||||
Bar string `json:"bar"`
|
||||
} `json:"nested"`
|
||||
}
|
||||
err := StrictJSON.BindBody([]byte(`{"foo": "FOO", "nested": {"bar": "BAR"}}`), &s)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "FOO", s.Foo)
|
||||
assert.Equal(t, "BAR", s.Nested.Bar)
|
||||
|
||||
err = StrictJSON.BindBody([]byte(`{"foo": "FOO", "nested": {"bar": "BAR", "what": "this"}}`), &s)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "what")
|
||||
}
|
||||
|
||||
func TestStrictJSONBindingBindNilValidator(t *testing.T) {
|
||||
type fooStruct struct {
|
||||
Foo string `json:"foo" binding:"required"`
|
||||
}
|
||||
|
||||
// Restore the global validator so other tests aren't affected.
|
||||
orig := Validator
|
||||
Validator = nil
|
||||
t.Cleanup(func() { Validator = orig })
|
||||
|
||||
// Empty body: decoding fails with an error and must not panic,
|
||||
// even though no validator is configured.
|
||||
s := fooStruct{}
|
||||
req := requestWithBody(http.MethodPost, "/", "")
|
||||
assert.NotPanics(t, func() {
|
||||
err := StrictJSON.Bind(req, &s)
|
||||
require.Error(t, err)
|
||||
assert.ErrorIs(t, err, io.EOF)
|
||||
})
|
||||
|
||||
// Same for BindBody.
|
||||
s = fooStruct{}
|
||||
assert.NotPanics(t, func() {
|
||||
err := StrictJSON.BindBody([]byte(""), &s)
|
||||
require.Error(t, err)
|
||||
})
|
||||
|
||||
// Sanity check: a valid body with a nil validator decodes fine and
|
||||
// skips validation entirely (so the `required` tag isn't enforced).
|
||||
s = fooStruct{}
|
||||
req = requestWithBody(http.MethodPost, "/", `{}`)
|
||||
assert.NotPanics(t, func() {
|
||||
require.NoError(t, StrictJSON.Bind(req, &s))
|
||||
})
|
||||
assert.Empty(t, s.Foo)
|
||||
}
|
||||
|
||||
func TestStrictJSONBindingDoesNotAffectJSON(t *testing.T) {
|
||||
var s struct {
|
||||
Foo string `json:"foo"`
|
||||
}
|
||||
body := []byte(`{"foo": "FOO", "what": "this"}`)
|
||||
require.Error(t, StrictJSON.BindBody(body, &s))
|
||||
require.NoError(t, JSON.BindBody(body, &s))
|
||||
assert.False(t, EnableDecoderDisallowUnknownFields)
|
||||
}
|
||||
|
||||
func TestCustomJsonCodec(t *testing.T) {
|
||||
// Restore json encoding configuration after testing
|
||||
oldMarshal := json.API
|
||||
|
||||
14
context.go
14
context.go
@ -786,6 +786,12 @@ func (c *Context) BindJSON(obj any) error {
|
||||
return c.MustBindWith(obj, binding.JSON)
|
||||
}
|
||||
|
||||
// BindStrictJSON is a shortcut for c.MustBindWith(obj, binding.StrictJSON).
|
||||
// Unlike BindJSON, it rejects JSON objects containing fields that are unknown to obj.
|
||||
func (c *Context) BindStrictJSON(obj any) error {
|
||||
return c.MustBindWith(obj, binding.StrictJSON)
|
||||
}
|
||||
|
||||
// BindXML is a shortcut for c.MustBindWith(obj, binding.XML).
|
||||
func (c *Context) BindXML(obj any) error {
|
||||
return c.MustBindWith(obj, binding.XML)
|
||||
@ -890,6 +896,14 @@ func (c *Context) ShouldBindJSON(obj any) error {
|
||||
return c.ShouldBindWith(obj, binding.JSON)
|
||||
}
|
||||
|
||||
// ShouldBindStrictJSON is a shortcut for c.ShouldBindWith(obj, binding.StrictJSON).
|
||||
// Unlike ShouldBindJSON, it returns an error if the JSON body contains fields
|
||||
// that are unknown to obj. It only affects this call, whereas
|
||||
// EnableDecoderDisallowUnknownFields applies to every JSON binding.
|
||||
func (c *Context) ShouldBindStrictJSON(obj any) error {
|
||||
return c.ShouldBindWith(obj, binding.StrictJSON)
|
||||
}
|
||||
|
||||
// ShouldBindXML is a shortcut for c.ShouldBindWith(obj, binding.XML).
|
||||
// It works like ShouldBindJSON but binds the request body as XML data.
|
||||
func (c *Context) ShouldBindXML(obj any) error {
|
||||
|
||||
@ -2383,6 +2383,41 @@ func TestContextBindWithJSON(t *testing.T) {
|
||||
assert.Equal(t, 0, w.Body.Len())
|
||||
}
|
||||
|
||||
func TestContextBindWithStrictJSON(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
|
||||
c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))
|
||||
c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
|
||||
|
||||
var obj struct {
|
||||
Foo string `json:"foo"`
|
||||
Bar string `json:"bar"`
|
||||
}
|
||||
require.NoError(t, c.BindStrictJSON(&obj))
|
||||
assert.Equal(t, "foo", obj.Bar)
|
||||
assert.Equal(t, "bar", obj.Foo)
|
||||
assert.Equal(t, 0, w.Body.Len())
|
||||
assert.False(t, c.IsAborted())
|
||||
}
|
||||
|
||||
func TestContextBindWithStrictJSONUnknownField(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
|
||||
c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "what":"this"}`))
|
||||
c.Request.Header.Add("Content-Type", MIMEJSON)
|
||||
|
||||
var obj struct {
|
||||
Foo string `json:"foo"`
|
||||
}
|
||||
require.Error(t, c.BindStrictJSON(&obj))
|
||||
c.Writer.WriteHeaderNow()
|
||||
|
||||
assert.Equal(t, http.StatusBadRequest, w.Code)
|
||||
assert.True(t, c.IsAborted())
|
||||
}
|
||||
|
||||
func TestContextBindWithXML(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
@ -2553,6 +2588,40 @@ func TestContextShouldBindWithJSON(t *testing.T) {
|
||||
assert.Equal(t, 0, w.Body.Len())
|
||||
}
|
||||
|
||||
func TestContextShouldBindWithStrictJSON(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
|
||||
c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))
|
||||
c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
|
||||
|
||||
var obj struct {
|
||||
Foo string `json:"foo"`
|
||||
Bar string `json:"bar"`
|
||||
}
|
||||
require.NoError(t, c.ShouldBindStrictJSON(&obj))
|
||||
assert.Equal(t, "foo", obj.Bar)
|
||||
assert.Equal(t, "bar", obj.Foo)
|
||||
assert.Equal(t, 0, w.Body.Len())
|
||||
}
|
||||
|
||||
func TestContextShouldBindWithStrictJSONUnknownField(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
|
||||
c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "what":"this"}`))
|
||||
c.Request.Header.Add("Content-Type", MIMEJSON)
|
||||
|
||||
var obj struct {
|
||||
Foo string `json:"foo"`
|
||||
}
|
||||
err := c.ShouldBindStrictJSON(&obj)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "what")
|
||||
assert.False(t, c.IsAborted())
|
||||
assert.Equal(t, 0, w.Body.Len())
|
||||
}
|
||||
|
||||
func TestContextShouldBindWithXML(t *testing.T) {
|
||||
w := httptest.NewRecorder()
|
||||
c, _ := CreateTestContext(w)
|
||||
|
||||
@ -865,10 +865,10 @@ Note that you need to set the corresponding binding tag on all fields you want t
|
||||
Also, Gin provides two sets of methods for binding:
|
||||
|
||||
- **Type** - Must bind
|
||||
- **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML`
|
||||
- **Methods** - `Bind`, `BindJSON`, `BindStrictJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML`
|
||||
- **Behavior** - These methods use `MustBindWith` under the hood. If there is a binding error, the request is aborted with `c.AbortWithError(400, err).SetType(ErrorTypeBind)`. This sets the response status code to 400 and the `Content-Type` header is set to `text/plain; charset=utf-8`. Note that if you try to set the response code after this, it will result in a warning `[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422`. If you wish to have greater control over the behavior, consider using the `ShouldBind` equivalent method.
|
||||
- **Type** - Should bind
|
||||
- **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`, `ShouldBindTOML`,
|
||||
- **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindStrictJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`, `ShouldBindTOML`,
|
||||
- **Behavior** - These methods use `ShouldBindWith` under the hood. If there is a binding error, the error is returned and it is the developer's responsibility to handle the request and error appropriately.
|
||||
|
||||
When using the Bind-method, Gin tries to infer the binder depending on the Content-Type header. If you are sure what you are binding, you can use `MustBindWith` or `ShouldBindWith`.
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user