Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tonic: Configurable max body bytes #61

Merged
merged 1 commit into from
Mar 8, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions tonic/tonic.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import (
validator "gopkg.in/go-playground/validator.v9"
)

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

// Fields tags used by tonic.
const (
Expand Down Expand Up @@ -86,15 +86,20 @@ func DefaultErrorHook(c *gin.Context, e error) (int, interface{}) {
// It uses Gin JSON binding to bind the body parameters of the request
// to the input object of the handler.
// Ir teturns an error if Gin binding fails.
func DefaultBindingHook(c *gin.Context, i interface{}) error {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, MaxBodyBytes)
if c.Request.ContentLength == 0 || c.Request.Method == http.MethodGet {
var DefaultBindingHook BindHook = DefaultBindingHookMaxBodyBytes(DefaultMaxBodyBytes)

// DefaultBindingHookMaxBodyBytes returns a BindHook with the default logic, with configurable MaxBodyBytes.
func DefaultBindingHookMaxBodyBytes(maxBodyBytes int64) BindHook {
return func(c *gin.Context, i interface{}) error {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBodyBytes)
if c.Request.ContentLength == 0 || c.Request.Method == http.MethodGet {
return nil
}
if err := c.ShouldBindWith(i, binding.JSON); err != nil && err != io.EOF {
return fmt.Errorf("error parsing request body: %s", err.Error())
}
return nil
}
if err := c.ShouldBindWith(i, binding.JSON); err != nil && err != io.EOF {
return fmt.Errorf("error parsing request body: %s", err.Error())
}
return nil
}

// DefaultRenderHook is the default render hook.
Expand Down