From 402f6b9d696a3de25460253e83d389e2efed3cb6 Mon Sep 17 00:00:00 2001
From: Aliaksandr Valialkin <valyala@victoriametrics.com>
Date: Fri, 31 Mar 2023 22:41:02 -0700
Subject: [PATCH] lib/fs: follow-up for
 ec45f1bc5fd1e8d4bffee3d599075961bd96d235

Properly close response body before checking for the response code.

Updates https://github.com/VictoriaMetrics/VictoriaMetrics/issues/4034
---
 lib/fs/fs.go | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/lib/fs/fs.go b/lib/fs/fs.go
index a42cb988cc..d474bd087d 100644
--- a/lib/fs/fs.go
+++ b/lib/fs/fs.go
@@ -439,13 +439,14 @@ func ReadFileOrHTTP(path string) ([]byte, error) {
 		if err != nil {
 			return nil, fmt.Errorf("cannot fetch %q: %w", path, err)
 		}
-
-		if resp.StatusCode != http.StatusOK {
-			return nil, fmt.Errorf("unexpected status code when fetching %q: %d, expecting %d", path, resp.StatusCode, http.StatusOK)
-		}
-
 		data, err := io.ReadAll(resp.Body)
 		_ = resp.Body.Close()
+		if resp.StatusCode != http.StatusOK {
+			if len(data) > 4*1024 {
+				data = data[:4*1024]
+			}
+			return nil, fmt.Errorf("unexpected status code when fetching %q: %d, expecting %d; response: %q", path, resp.StatusCode, http.StatusOK, data)
+		}
 		if err != nil {
 			return nil, fmt.Errorf("cannot read %q: %s", path, err)
 		}