diff --git a/modules/caddyhttp/server.go b/modules/caddyhttp/server.go index cf176094716..54e8d2dc828 100644 --- a/modules/caddyhttp/server.go +++ b/modules/caddyhttp/server.go @@ -319,7 +319,8 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // so we can track the number of bytes read from it var bodyReader *lengthReader if r.Body != nil { - bodyReader = &lengthReader{Source: r.Body} + bodyReader = getLengthReader(r.Body) + defer putLengthReader(bodyReader) r.Body = bodyReader } @@ -911,6 +912,24 @@ type lengthReader struct { Length int } +var lengthReaderPool = sync.Pool{ + New: func() interface{} { + return &lengthReader{} + }, +} + +func getLengthReader(source io.ReadCloser) *lengthReader { + reader := lengthReaderPool.Get().(*lengthReader) + reader.Source = source + return reader +} + +func putLengthReader(reader *lengthReader) { + reader.Source = nil + reader.Length = 0 + lengthReaderPool.Put(reader) +} + func (r *lengthReader) Read(b []byte) (int, error) { n, err := r.Source.Read(b) r.Length += n