Make sure to drain body upon an error (#7197)
Also cleanup redundant code and use it at a common placemaster
parent
2d168b532b
commit
817269475f
@ -0,0 +1,52 @@ |
||||
/* |
||||
* Minio Cloud Storage, (C) 2019 Minio, Inc. |
||||
* |
||||
* Licensed under the Apache License, Version 2.0 (the "License"); |
||||
* you may not use this file except in compliance with the License. |
||||
* You may obtain a copy of the License at |
||||
* |
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
* |
||||
* Unless required by applicable law or agreed to in writing, software |
||||
* distributed under the License is distributed on an "AS IS" BASIS, |
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
||||
* See the License for the specific language governing permissions and |
||||
* limitations under the License. |
||||
*/ |
||||
|
||||
package http |
||||
|
||||
import ( |
||||
"io" |
||||
"io/ioutil" |
||||
"sync" |
||||
) |
||||
|
||||
var b512pool = sync.Pool{ |
||||
New: func() interface{} { |
||||
buf := make([]byte, 512) |
||||
return &buf |
||||
}, |
||||
} |
||||
|
||||
// DrainBody close non nil response with any response Body.
|
||||
// convenient wrapper to drain any remaining data on response body.
|
||||
//
|
||||
// Subsequently this allows golang http RoundTripper
|
||||
// to re-use the same connection for future requests.
|
||||
func DrainBody(respBody io.ReadCloser) { |
||||
// Callers should close resp.Body when done reading from it.
|
||||
// If resp.Body is not closed, the Client's underlying RoundTripper
|
||||
// (typically Transport) may not be able to re-use a persistent TCP
|
||||
// connection to the server for a subsequent "keep-alive" request.
|
||||
if respBody != nil { |
||||
// Drain any remaining Body and then close the connection.
|
||||
// Without this closing connection would disallow re-using
|
||||
// the same connection for future uses.
|
||||
// - http://stackoverflow.com/a/17961593/4465767
|
||||
bufp := b512pool.Get().(*[]byte) |
||||
defer b512pool.Put(bufp) |
||||
io.CopyBuffer(ioutil.Discard, respBody, *bufp) |
||||
respBody.Close() |
||||
} |
||||
} |
Loading…
Reference in new issue