Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 12, 22:00 UTC
caddyhttp: Use sync.Pool to reduce lengthReader allocations (#5848)
* 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>
Harish Shan committed
Oct 17, 2023 at 02:12 UTC
c8559c448537969376623be9d352949b59907b0e
1 file changed
+20
-1
modules/caddyhttp/server.go
+20
-1
@@ -318,7 +318,8 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
318
// so we can track the number of bytes read from it
319
var bodyReader *lengthReader
320
if r.Body != nil {
321
- bodyReader = &lengthReader{Source: r.Body}
321
+ bodyReader = getLengthReader(r.Body)
322
+ defer putLengthReader(bodyReader)
323
r.Body = bodyReader
324
}
325
@@ -902,6 +903,24 @@ type lengthReader struct {
903
Length int
904
}
905
906
+var lengthReaderPool = sync.Pool{
907
+ New: func() interface{} {
908
+ return &lengthReader{}
909
+ },
910
+}
911
+
912
+func getLengthReader(source io.ReadCloser) *lengthReader {
913
+ reader := lengthReaderPool.Get().(*lengthReader)
914
+ reader.Source = source
915
+ return reader
916
+}
917
+
918
+func putLengthReader(reader *lengthReader) {
919
+ reader.Source = nil
920
+ reader.Length = 0
921
+ lengthReaderPool.Put(reader)
922
+}
923
+
924
func (r *lengthReader) Read(b []byte) (int, error) {
925
n, err := r.Source.Read(b)
926
r.Length += n