github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/plugin/bodylmt/middleware.go (about)

     1  package bodylmt
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"code.cloudfoundry.org/bytefmt"
     7  	"github.com/hellofresh/janus/pkg/errors"
     8  	log "github.com/sirupsen/logrus"
     9  )
    10  
    11  var (
    12  	// ErrRequestEntityTooLarge is thrown when a body size is bigger then the limit specified
    13  	ErrRequestEntityTooLarge = errors.New(http.StatusRequestEntityTooLarge, http.StatusText(http.StatusRequestEntityTooLarge))
    14  )
    15  
    16  // NewBodyLimitMiddleware creates a new body limit middleware
    17  func NewBodyLimitMiddleware(limit string) func(http.Handler) http.Handler {
    18  	return func(handler http.Handler) http.Handler {
    19  		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    20  			log.WithField("limit", limit).Debug("Starting body limit middleware")
    21  			limit, err := bytefmt.ToBytes(limit)
    22  			if err != nil {
    23  				log.WithError(err).WithField("limit", limit).Error("invalid body-limit")
    24  			}
    25  
    26  			// Based on content length
    27  			if r.ContentLength > int64(limit) {
    28  				errors.Handler(w, r, ErrRequestEntityTooLarge)
    29  				return
    30  			}
    31  
    32  			r.Body = http.MaxBytesReader(w, r.Body, int64(limit))
    33  			handler.ServeHTTP(w, r)
    34  		})
    35  	}
    36  }