Skip to content

Commit

Permalink
caddyhttp: Use sync.Pool to reduce lengthReader allocations (#5848)
Browse files Browse the repository at this point in the history
* Use sync.Pool to reduce lengthReader allocations

Signed-off-by: Harish Shan <140232061+perhapsmaple@users.noreply.github.com>

* Add defer putLengthReader to prevent leak

Signed-off-by: Harish Shan <140232061+perhapsmaple@users.noreply.github.com>

* Cleanup in putLengthReader

Co-authored-by: Francis Lavoie <lavofr@gmail.com>

---------

Signed-off-by: Harish Shan <140232061+perhapsmaple@users.noreply.github.com>
Co-authored-by: Francis Lavoie <lavofr@gmail.com>
  • Loading branch information
perhapsmaple and francislavoie committed Oct 16, 2023
1 parent 24b0ecc commit c8559c4
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion modules/caddyhttp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,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
}

Expand Down Expand Up @@ -902,6 +903,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
Expand Down

0 comments on commit c8559c4

Please sign in to comment.