From a38b01275f69b7687a221fda556dd6d06422128c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Poniedzia=C5=82ek?= Date: Wed, 8 Jan 2025 09:37:02 +0100 Subject: [PATCH] More improvements in HTTP client * Use `http.DefaultTransport` * Set `MaxIdleConnsPerHost` equal to the `MaxIdleConns` * Drain and close response body in defer function --- pkg/target/http.go | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/pkg/target/http.go b/pkg/target/http.go index a8d4042a..7ad5c098 100644 --- a/pkg/target/http.go +++ b/pkg/target/http.go @@ -168,7 +168,8 @@ func newHTTPTarget( if err1 != nil { return nil, err1 } - transport := &http.Transport{} + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.MaxIdleConnsPerHost = transport.MaxIdleConns tlsConfig, err2 := common.CreateTLSConfiguration(certFile, keyFile, caFile, skipVerifyTLS) if err2 != nil { @@ -398,12 +399,12 @@ func (ht *HTTPTarget) Write(messages []*models.Message) (*models.TargetWriteResu continue } - // Ensure response body is always closed - if resp.StatusCode >= 200 && resp.StatusCode < 300 { - // Drain and close the body for successful responses - _, _ = io.Copy(io.Discard, resp.Body) + defer func() { + io.Copy(io.Discard, resp.Body) resp.Body.Close() + }() + if resp.StatusCode >= 200 && resp.StatusCode < 300 { for _, msg := range goodMsgs { if msg.AckFunc != nil { // Ack successful messages msg.AckFunc() @@ -415,8 +416,6 @@ func (ht *HTTPTarget) Write(messages []*models.Message) (*models.TargetWriteResu // Process non-2xx responses responseBody, err := io.ReadAll(resp.Body) - _, _ = io.Copy(io.Discard, resp.Body) - resp.Body.Close() // Explicitly close the body after reading if err != nil { failed = append(failed, goodMsgs...)