Skip to content

Commit 66ad463

Browse files
authored
tonic: Configurable max body bytes (#61)
1 parent 66acbcf commit 66ad463

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

tonic/tonic.go

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@ import (
1717
validator "gopkg.in/go-playground/validator.v9"
1818
)
1919

20-
// MaxBodyBytes is the maximum allowed size of a request body in bytes.
21-
const MaxBodyBytes = 256 * 1024
20+
// DefaultMaxBodyBytes is the maximum allowed size of a request body in bytes.
21+
const DefaultMaxBodyBytes = 256 * 1024
2222

2323
// Fields tags used by tonic.
2424
const (
@@ -86,15 +86,20 @@ func DefaultErrorHook(c *gin.Context, e error) (int, interface{}) {
8686
// It uses Gin JSON binding to bind the body parameters of the request
8787
// to the input object of the handler.
8888
// Ir teturns an error if Gin binding fails.
89-
func DefaultBindingHook(c *gin.Context, i interface{}) error {
90-
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, MaxBodyBytes)
91-
if c.Request.ContentLength == 0 || c.Request.Method == http.MethodGet {
89+
var DefaultBindingHook BindHook = DefaultBindingHookMaxBodyBytes(DefaultMaxBodyBytes)
90+
91+
// DefaultBindingHookMaxBodyBytes returns a BindHook with the default logic, with configurable MaxBodyBytes.
92+
func DefaultBindingHookMaxBodyBytes(maxBodyBytes int64) BindHook {
93+
return func(c *gin.Context, i interface{}) error {
94+
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBodyBytes)
95+
if c.Request.ContentLength == 0 || c.Request.Method == http.MethodGet {
96+
return nil
97+
}
98+
if err := c.ShouldBindWith(i, binding.JSON); err != nil && err != io.EOF {
99+
return fmt.Errorf("error parsing request body: %s", err.Error())
100+
}
92101
return nil
93102
}
94-
if err := c.ShouldBindWith(i, binding.JSON); err != nil && err != io.EOF {
95-
return fmt.Errorf("error parsing request body: %s", err.Error())
96-
}
97-
return nil
98103
}
99104

100105
// DefaultRenderHook is the default render hook.

0 commit comments

Comments
 (0)