Skip to content

Commit

Permalink
feature: Keep the memory usage of the service at a stable level (#1216)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
Rennbon and erikdubbelboer committed Mar 3, 2022
1 parent 15262ec commit f54ffa1
Showing 1 changed file with 18 additions and 0 deletions.
18 changes: 18 additions & 0 deletions http.go
Expand Up @@ -17,6 +17,18 @@ import (
"github.com/valyala/bytebufferpool"
)

var (
requestBodyPoolSizeLimit = -1
responseBodyPoolSizeLimit = -1
)

// SetBodySizePoolLimit set the max body size for bodies to be returned to the pool.
// If the body size is larger it will be released instead of put back into the pool for reuse.
func SetBodySizePoolLimit(reqBodyLimit, respBodyLimit int) {
requestBodyPoolSizeLimit = reqBodyLimit
responseBodyPoolSizeLimit = respBodyLimit
}

// Request represents HTTP request.
//
// It is forbidden copying Request instances. Create new instances
Expand Down Expand Up @@ -957,6 +969,9 @@ func readMultipartForm(r io.Reader, boundary string, size, maxInMemoryFileSize i

// Reset clears request contents.
func (req *Request) Reset() {
if requestBodyPoolSizeLimit >= 0 && req.body != nil {
req.ReleaseBody(requestBodyPoolSizeLimit)
}
req.Header.Reset()
req.resetSkipHeader()
req.timeout = 0
Expand Down Expand Up @@ -986,6 +1001,9 @@ func (req *Request) RemoveMultipartFormFiles() {

// Reset clears response contents.
func (resp *Response) Reset() {
if responseBodyPoolSizeLimit >= 0 && resp.body != nil {
resp.ReleaseBody(responseBodyPoolSizeLimit)
}
resp.Header.Reset()
resp.resetSkipHeader()
resp.SkipBody = false
Expand Down

0 comments on commit f54ffa1

Please sign in to comment.