Skip to content
Myr

chore(bind): return 413 status code when error is `http.MaxBytesError` (#4227)

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

* Bind: return 413 status code when error is `http.MaxBytesError` The Go standard library includes a method `http.MaxBytesReader` that allows limiting the request body. For example, users can create a middleware like: ```go func MiddlewareMaxBodySize(c *gin.Context) { // Limit request body to 100 bytes c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 100) c.Next() } ``` When the body exceeds the limit, reading from the request body returns an error of type `http.MaxBytesError`. This PR makes sure that when the error is of kind `http.MaxBytesError`, Gin returns the correct status code 413 (Request Entity Too Large) instead of a generic 400 (Bad Request). * Disable test when using sonic * Fix * Disable for go-json too * Add references to GitHub issues * Test that the response is 400 for sonic and go-json

authored by Alessandro (Ale) Segala · committed by GitHub · parent c4287b1 · Browse files · 6 files+80 added−24 removed
This commit

State

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

Diff stats

6 files+80 added−24 removed

  • other:+80 added−24 removed

6 files+80 added−24 removed

modified:internal/json/go_json.go+3 added
18 unmodified lines
19 NewDecoder = json.NewDecoder20 // NewEncoder is exported by gin/json package.21 NewEncoder = json.NewEncoder22)2324// Package indicates what library is being used for JSON encoding.25const Package = "github.com/goccy/go-json"
modified:internal/json/json.go+3 added
18 unmodified lines
19 NewDecoder = json.NewDecoder20 // NewEncoder is exported by gin/json package.21 NewEncoder = json.NewEncoder22)2324// Package indicates what library is being used for JSON encoding.25const Package = "encoding/json"
modified:internal/json/jsoniter.go+3 added
19 unmodified lines
20 NewDecoder = json.NewDecoder21 // NewEncoder is exported by gin/json package.22 NewEncoder = json.NewEncoder23)2425// Package indicates what library is being used for JSON encoding.26const Package = "github.com/json-iterator/go"
modified:internal/json/sonic.go+3 added
19 unmodified lines
20 NewDecoder = json.NewDecoder21 // NewEncoder is exported by gin/json package.22 NewEncoder = json.NewEncoder23)2425// Package indicates what library is being used for JSON encoding.26const Package = "github.com/bytedance/sonic"
modified:context_test.go+55 added-22 removed
26 unmodified lines
27 "time"2829 "github.com/gin-contrib/sse"30 "github.com/gin-gonic/gin/binding"31 "github.com/gin-gonic/gin/internal/json"32 testdata "github.com/gin-gonic/gin/testdata/protoexample"33 "github.com/stretchr/testify/assert"34 "github.com/stretchr/testify/require"35 "google.golang.org/protobuf/proto"
635 unmodified lines
671}672673func TestContextQueryAndPostForm(t *testing.T) {674 c, _ := CreateTestContext(httptest.NewRecorder())674 body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")675 body := strings.NewReader("foo=bar&page=11&both=&foo=second")676 c.Request, _ = http.NewRequest(http.MethodPost,677 "/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14", body)678 c.Request.Header.Add("Content-Type", MIMEPOSTForm)679
266 unmodified lines
946947 c.JSONP(http.StatusCreated, H{"foo": "bar"})948949 assert.Equal(t, http.StatusCreated, w.Code)949 assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String())950 assert.JSONEq(t, `{"foo":"bar"}`, w.Body.String())951 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))952}953954// Tests that no JSON is rendered if code is 204
17 unmodified lines
972 c.Header("Content-Type", "application/vnd.api+json")973 c.JSON(http.StatusCreated, H{"foo": "bar"})974975 assert.Equal(t, http.StatusCreated, w.Code)975 assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String())976 assert.JSONEq(t, `{"foo":"bar"}`, w.Body.String())977 assert.Equal(t, "application/vnd.api+json", w.Header().Get("Content-Type"))978}979980// Tests that no Custom JSON is rendered if code is 204
451 unmodified lines
1432 Data: H{"foo": "bar"},1433 })14341435 assert.Equal(t, http.StatusOK, w.Code)1435 assert.JSONEq(t, "{\"foo\":\"bar\"}", w.Body.String())1436 assert.JSONEq(t, `{"foo":"bar"}`, w.Body.String())1437 assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))1438}14391440func TestContextNegotiationWithXML(t *testing.T) {
407 unmodified lines
18481849 assert.Equal(t, "application/json", c.ContentType())1850}18511852func TestContextBindRequestTooLarge(t *testing.T) {1853 // When using sonic or go-json as JSON encoder, they do not propagate the http.MaxBytesError error1854 // The response will fail with a generic 400 instead of 4131855 // https://github.com/goccy/go-json/issues/4851856 // https://github.com/bytedance/sonic/issues/8001857 var expectedCode int1858 switch json.Package {1859 case "github.com/goccy/go-json", "github.com/bytedance/sonic":1860 expectedCode = http.StatusBadRequest1861 default:1862 expectedCode = http.StatusRequestEntityTooLarge1863 }18641865 w := httptest.NewRecorder()1866 c, _ := CreateTestContext(w)18671868 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))1869 c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 10)18701871 var obj struct {1872 Foo string `json:"foo"`1873 Bar string `json:"bar"`1874 }1875 require.Error(t, c.BindJSON(&obj))1876 c.Writer.WriteHeaderNow()18771878 assert.Empty(t, obj.Bar)1879 assert.Empty(t, obj.Foo)1880 assert.Equal(t, expectedCode, w.Code)1881 assert.True(t, c.IsAborted())1882}18831884func TestContextAutoBindJSON(t *testing.T) {1885 c, _ := CreateTestContext(httptest.NewRecorder())1853 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1886 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))1887 c.Request.Header.Add("Content-Type", MIMEJSON)18881889 var obj struct {1890 Foo string `json:"foo"`
8 unmodified lines
1899func TestContextBindWithJSON(t *testing.T) {1900 w := httptest.NewRecorder()1901 c, _ := CreateTestContext(w)19021870 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))1903 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))1904 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type19051906 var obj struct {1907 Foo string `json:"foo"`
8 unmodified lines
1916func TestContextBindWithXML(t *testing.T) {1917 w := httptest.NewRecorder()1918 c, _ := CreateTestContext(w)19191887 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>1920 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`<?xml version="1.0" encoding="UTF-8"?>1921 <root>1922 <foo>FOO</foo>1923 <bar>BAR</bar>1924 </root>`))
58 unmodified lines
1983func TestContextBindWithQuery(t *testing.T) {1984 w := httptest.NewRecorder()1985 c, _ := CreateTestContext(w)19861954 c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))1987 c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo", strings.NewReader("foo=unused"))19881989 var obj struct {1990 Foo string `form:"foo"`1991 Bar string `form:"bar"`
7 unmodified lines
1999func TestContextBindWithYAML(t *testing.T) {2000 w := httptest.NewRecorder()2001 c, _ := CreateTestContext(w)20021970 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo: bar\nbar: foo"))2003 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader("foo: bar\nbar: foo"))2004 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type20052006 var obj struct {2007 Foo string `yaml:"foo"`
8 unmodified lines
2016func TestContextBindWithTOML(t *testing.T) {2017 w := httptest.NewRecorder()2018 c, _ := CreateTestContext(w)20191987 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo = 'bar'\nbar = 'foo'"))2020 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader("foo = 'bar'\nbar = 'foo'"))2021 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type20222023 var obj struct {2024 Foo string `toml:"foo"`
8 unmodified lines
2033func TestContextBadAutoBind(t *testing.T) {2034 w := httptest.NewRecorder()2035 c, _ := CreateTestContext(w)20362004 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))2037 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", strings.NewReader("\"foo\":\"bar\", \"bar\":\"foo\"}"))2038 c.Request.Header.Add("Content-Type", MIMEJSON)2039 var obj struct {2040 Foo string `json:"foo"`2041 Bar string `json:"bar"`
10 unmodified lines
2052}20532054func TestContextAutoShouldBindJSON(t *testing.T) {2055 c, _ := CreateTestContext(httptest.NewRecorder())2023 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))2056 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))2057 c.Request.Header.Add("Content-Type", MIMEJSON)20582059 var obj struct {2060 Foo string `json:"foo"`
8 unmodified lines
2069func TestContextShouldBindWithJSON(t *testing.T) {2070 w := httptest.NewRecorder()2071 c, _ := CreateTestContext(w)20722040 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))2073 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))2074 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type20752076 var obj struct {2077 Foo string `json:"foo"`
8 unmodified lines
2086func TestContextShouldBindWithXML(t *testing.T) {2087 w := httptest.NewRecorder()2088 c, _ := CreateTestContext(w)20892057 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>2090 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`<?xml version="1.0" encoding="UTF-8"?>2091 <root>2092 <foo>FOO</foo>2093 <bar>BAR</bar>2094 </root>`))
58 unmodified lines
2153func TestContextShouldBindWithQuery(t *testing.T) {2154 w := httptest.NewRecorder()2155 c, _ := CreateTestContext(w)21562124 c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo&Foo=bar1&Bar=foo1", bytes.NewBufferString("foo=unused"))2157 c.Request, _ = http.NewRequest(http.MethodPost, "/?foo=bar&bar=foo&Foo=bar1&Bar=foo1", strings.NewReader("foo=unused"))21582159 var obj struct {2160 Foo string `form:"foo"`2161 Bar string `form:"bar"`
11 unmodified lines
2173func TestContextShouldBindWithYAML(t *testing.T) {2174 w := httptest.NewRecorder()2175 c, _ := CreateTestContext(w)21762144 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo: bar\nbar: foo"))2177 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader("foo: bar\nbar: foo"))2178 c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type21792180 var obj struct {2181 Foo string `yaml:"foo"`
8 unmodified lines
2190func TestContextShouldBindWithTOML(t *testing.T) {2191 w := httptest.NewRecorder()2192 c, _ := CreateTestContext(w)21932161 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("foo='bar'\nbar= 'foo'"))2194 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader("foo='bar'\nbar= 'foo'"))2195 c.Request.Header.Add("Content-Type", MIMETOML) // set fake content-type21962197 var obj struct {2198 Foo string `toml:"foo"`
8 unmodified lines
2207func TestContextBadAutoShouldBind(t *testing.T) {2208 w := httptest.NewRecorder()2209 c, _ := CreateTestContext(w)22102178 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))2211 c.Request, _ = http.NewRequest(http.MethodPost, "http://example.com", strings.NewReader(`"foo":"bar", "bar":"foo"}`))2212 c.Request.Header.Add("Content-Type", MIMEJSON)2213 var obj struct {2214 Foo string `json:"foo"`2215 Bar string `json:"bar"`
55 unmodified lines
2271 {2272 w := httptest.NewRecorder()2273 c, _ := CreateTestContext(w)2274 c.Request, _ = http.NewRequest(2242 http.MethodPost, "http://example.com", bytes.NewBufferString(tt.bodyA),2275 http.MethodPost, "http://example.com", strings.NewReader(tt.bodyA),2276 )2277 // When it binds to typeA and typeB, it finds the body is2278 // not typeB but typeA.2279 objA := typeA{}
9 unmodified lines
2289 // not typeA but typeB.2290 w := httptest.NewRecorder()2291 c, _ := CreateTestContext(w)2292 c.Request, _ = http.NewRequest(2260 http.MethodPost, "http://example.com", bytes.NewBufferString(tt.bodyB),2293 http.MethodPost, "http://example.com", strings.NewReader(tt.bodyB),2294 )2295 objA := typeA{}2296 require.Error(t, c.ShouldBindBodyWith(&objA, tt.bindingA))2297 assert.NotEqual(t, typeA{"FOO"}, objA)
337 unmodified lines
2635}26362637func TestContextGolangContext(t *testing.T) {2638 c, _ := CreateTestContext(httptest.NewRecorder())2606 c.Request, _ = http.NewRequest(http.MethodPost, "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))2639 c.Request, _ = http.NewRequest(http.MethodPost, "/", strings.NewReader(`{"foo":"bar", "bar":"foo"}`))2640 require.NoError(t, c.Err())2641 assert.Nil(t, c.Done())2642 ti, ok := c.Deadline()2643 assert.Equal(t, time.Time{}, ti)
39 unmodified lines
2683}26842685func TestContextGetRawData(t *testing.T) {2686 c, _ := CreateTestContext(httptest.NewRecorder())2654 body := bytes.NewBufferString("Fetch binary post data")2687 body := strings.NewReader("Fetch binary post data")2688 c.Request, _ = http.NewRequest(http.MethodPost, "/", body)2689 c.Request.Header.Add("Content-Type", MIMEPOSTForm)26902691 data, err := c.GetRawData()
593 unmodified lines
modified:context.go+13 added-2 removed
767 unmodified lines
768// MustBindWith binds the passed struct pointer using the specified binding engine.769// It will abort the request with HTTP 400 if any error occurs.770// See the binding package.771func (c *Context) MustBindWith(obj any, b binding.Binding) error {772 if err := c.ShouldBindWith(obj, b); err != nil {773 c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck772 err := c.ShouldBindWith(obj, b)773 if err != nil {774 var maxBytesErr *http.MaxBytesError775776 // Note: When using sonic or go-json as JSON encoder, they do not propagate the http.MaxBytesError error777 // https://github.com/goccy/go-json/issues/485778 // https://github.com/bytedance/sonic/issues/800779 switch {780 case errors.As(err, &maxBytesErr):781 c.AbortWithError(http.StatusRequestEntityTooLarge, err).SetType(ErrorTypeBind) //nolint: errcheck782 default:783 c.AbortWithError(http.StatusBadRequest, err).SetType(ErrorTypeBind) //nolint: errcheck784 }785 return err786 }787 return nil788}
596 unmodified lines