1
0

bodylimit.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package middleware
  2. import (
  3. "net/http"
  4. "strings"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // MaxBodyBytes caps the request body size for state-changing requests. It wraps
  8. // the body in an http.MaxBytesReader so that any handler reading it (gin's
  9. // ShouldBind, manual io.ReadAll, etc.) receives an error once the limit is
  10. // exceeded, which the existing bind-failure path reports as a 400 rather than
  11. // allocating an unbounded buffer or starting a long DB transaction.
  12. //
  13. // Methods without a body (GET/HEAD/OPTIONS/TRACE) and a non-positive limit are
  14. // passed through untouched. Paths ending in one of skipSuffixes are also passed
  15. // through uncapped — these are routes that legitimately accept a large upload
  16. // (e.g. database restore, which streams a multi-MiB SQLite file).
  17. func MaxBodyBytes(limit int64, skipSuffixes ...string) gin.HandlerFunc {
  18. return func(c *gin.Context) {
  19. if limit > 0 {
  20. switch c.Request.Method {
  21. case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace:
  22. default:
  23. if c.Request.Body != nil && !hasAnySuffix(c.Request.URL.Path, skipSuffixes) {
  24. c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, limit)
  25. }
  26. }
  27. }
  28. c.Next()
  29. }
  30. }
  31. func hasAnySuffix(path string, suffixes []string) bool {
  32. for _, suffix := range suffixes {
  33. if suffix != "" && strings.HasSuffix(path, suffix) {
  34. return true
  35. }
  36. }
  37. return false
  38. }