gin/internal/json/json.go
Alessandro (Ale) Segala 40725d85ba
chore(bind): return 413 status code when error is http.MaxBytesError (#4227)
* 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
2025-05-25 20:36:33 +08:00

26 lines
765 B
Go

// Copyright 2017 Bo-Yi Wu. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
//go:build !jsoniter && !go_json && !(sonic && (linux || windows || darwin))
package json
import "encoding/json"
var (
// Marshal is exported by gin/json package.
Marshal = json.Marshal
// Unmarshal is exported by gin/json package.
Unmarshal = json.Unmarshal
// MarshalIndent is exported by gin/json package.
MarshalIndent = json.MarshalIndent
// NewDecoder is exported by gin/json package.
NewDecoder = json.NewDecoder
// NewEncoder is exported by gin/json package.
NewEncoder = json.NewEncoder
)
// Package indicates what library is being used for JSON encoding.
const Package = "encoding/json"