Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix excessive memory usage #562

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 13 additions & 1 deletion colly.go
Original file line number Diff line number Diff line change
Expand Up @@ -665,8 +665,20 @@ func (c *Collector) fetch(u, method string, depth int, requestData io.Reader, ct
return !request.abort
}

var response *Response
var err error
defer func() {
if response != nil {
response.Body = []byte{}
response.Headers = nil
response.Request = nil
response.Ctx = nil
response.Trace = nil
responsePool.Put(response)
}
}()
origURL := req.URL
response, err := c.backend.Cache(req, c.MaxBodySize, checkHeadersFunc, c.CacheDir)
response, err = c.backend.Cache(req, c.MaxBodySize, checkHeadersFunc, c.CacheDir)
if proxyURL, ok := req.Context().Value(ProxyURLKey).(string); ok {
request.ProxyURL = proxyURL
}
Expand Down
14 changes: 9 additions & 5 deletions http_backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ type httpBackend struct {
lock *sync.RWMutex
}

var responsePool = sync.Pool{New: func() interface{} {
return &Response{}
}}

type checkHeadersFunc func(statusCode int, header http.Header) bool

// LimitRule provides connection restrictions for domains.
Expand Down Expand Up @@ -210,11 +214,11 @@ func (h *httpBackend) Do(request *http.Request, bodySize int, checkHeadersFunc c
if err != nil {
return nil, err
}
return &Response{
StatusCode: res.StatusCode,
Body: body,
Headers: &res.Header,
}, nil
response := responsePool.Get().(*Response)
response.StatusCode = res.StatusCode
response.Body = body
response.Headers = &res.Header
return response, nil
}

func (h *httpBackend) Limit(rule *LimitRule) error {
Expand Down