From 6c406e98c98baf349cbd2b0588ae9c5874eaa4d2 Mon Sep 17 00:00:00 2001 From: MastewalB Date: Thu, 8 Oct 2026 06:55:15 +0300 Subject: [PATCH] feat: add StrictJSON binding --- binding/binding.go | 1 + binding/binding_nomsgpack.go | 1 + binding/json.go | 27 +++++++++-- binding/json_test.go | 93 ++++++++++++++++++++++++++++++++++++ context.go | 14 ++++++ context_test.go | 69 ++++++++++++++++++++++++++ docs/doc.md | 4 +- 7 files changed, 203 insertions(+), 6 deletions(-) diff --git a/binding/binding.go b/binding/binding.go index eced0ae2..b99603a9 100644 --- a/binding/binding.go +++ b/binding/binding.go @@ -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{} diff --git a/binding/binding_nomsgpack.go b/binding/binding_nomsgpack.go index ae364d79..bf028ddf 100644 --- a/binding/binding_nomsgpack.go +++ b/binding/binding_nomsgpack.go @@ -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{} diff --git a/binding/json.go b/binding/json.go index f4ae921a..d22b917c 100644 --- a/binding/json.go +++ b/binding/json.go @@ -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 { diff --git a/binding/json_test.go b/binding/json_test.go index 942ee3eb..df7e0382 100644 --- a/binding/json_test.go +++ b/binding/json_test.go @@ -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 diff --git a/context.go b/context.go index 582d00f2..9ccf9475 100644 --- a/context.go +++ b/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 { diff --git a/context_test.go b/context_test.go index b82e04d5..c17095c4 100644 --- a/context_test.go +++ b/context_test.go @@ -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) diff --git a/docs/doc.md b/docs/doc.md index 01edf52c..f513ae91 100644 --- a/docs/doc.md +++ b/docs/doc.md @@ -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`.