github.com/billybanfield/evergreen@v0.0.0-20170525200750-eeee692790f7/util/limited_reader.go (about)

     1  package util
     2  
     3  import (
     4  	"io"
     5  	"net/http"
     6  
     7  	"github.com/pkg/errors"
     8  )
     9  
    10  const maxRequestSize = 16 * 1024 * 1024 // 16 MB
    11  
    12  type requestReader struct {
    13  	req *http.Request
    14  	*io.LimitedReader
    15  }
    16  
    17  // NewRequestReader returns an io.ReadCloser closer for the body of an
    18  // *http.Request, using a limited reader internally to avoid unbounded
    19  // reading from the request body. The reader is limited to 16 megabytes.
    20  func NewRequestReader(req *http.Request) io.ReadCloser {
    21  	return &requestReader{
    22  		req: req,
    23  		LimitedReader: &io.LimitedReader{
    24  			R: req.Body,
    25  			N: maxRequestSize,
    26  		},
    27  	}
    28  }
    29  
    30  func (r *requestReader) Close() error {
    31  	return errors.WithStack(r.req.Body.Close())
    32  }