Skip to content

Commit f54ffa1

Browse files
feature: Keep the memory usage of the service at a stable level (#1216)
* feature: add request and response body size limit, it prevents the large body from slowly stretching the memory of the entire service * fix: http.go fmt * refact: optimize code naming * Update http.go Co-authored-by: Erik Dubbelboer <erik@dubbelboer.com> * Update http.go Co-authored-by: Erik Dubbelboer <erik@dubbelboer.com> * Update http.go Co-authored-by: Erik Dubbelboer <erik@dubbelboer.com> * Update http.go Co-authored-by: Erik Dubbelboer <erik@dubbelboer.com> * Update http.go Co-authored-by: Erik Dubbelboer <erik@dubbelboer.com> Co-authored-by: Erik Dubbelboer <erik@dubbelboer.com>
1 parent 15262ec commit f54ffa1

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

http.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,18 @@ import (
1717
"github.com/valyala/bytebufferpool"
1818
)
1919

20+
var (
21+
requestBodyPoolSizeLimit = -1
22+
responseBodyPoolSizeLimit = -1
23+
)
24+
25+
// SetBodySizePoolLimit set the max body size for bodies to be returned to the pool.
26+
// If the body size is larger it will be released instead of put back into the pool for reuse.
27+
func SetBodySizePoolLimit(reqBodyLimit, respBodyLimit int) {
28+
requestBodyPoolSizeLimit = reqBodyLimit
29+
responseBodyPoolSizeLimit = respBodyLimit
30+
}
31+
2032
// Request represents HTTP request.
2133
//
2234
// It is forbidden copying Request instances. Create new instances
@@ -957,6 +969,9 @@ func readMultipartForm(r io.Reader, boundary string, size, maxInMemoryFileSize i
957969

958970
// Reset clears request contents.
959971
func (req *Request) Reset() {
972+
if requestBodyPoolSizeLimit >= 0 && req.body != nil {
973+
req.ReleaseBody(requestBodyPoolSizeLimit)
974+
}
960975
req.Header.Reset()
961976
req.resetSkipHeader()
962977
req.timeout = 0
@@ -986,6 +1001,9 @@ func (req *Request) RemoveMultipartFormFiles() {
9861001

9871002
// Reset clears response contents.
9881003
func (resp *Response) Reset() {
1004+
if responseBodyPoolSizeLimit >= 0 && resp.body != nil {
1005+
resp.ReleaseBody(responseBodyPoolSizeLimit)
1006+
}
9891007
resp.Header.Reset()
9901008
resp.resetSkipHeader()
9911009
resp.SkipBody = false

0 commit comments

Comments
 (0)