Просмотр исходного кода

Fix Response::content_length_ not reflecting body size in Logger (Fix #2488)

Server::apply_ranges computed the correct Content-Length header for
body-based responses but never updated content_length_, so the
Logger callback always saw 0. Set content_length_ to the final body
size (post-range/post-compression) alongside the header.
yhirose 4 недель назад
Родитель
Сommit
06b8b91589
2 измененных файлов с 20 добавлено и 2 удалено
  1. 2 2
      httplib.h
  2. 18 0
      test/test.cc

+ 2 - 2
httplib.h

@@ -12323,8 +12323,8 @@ inline void Server::apply_ranges(const Request &req, Response &res,
       }
     }
 
-    auto length = std::to_string(res.body.size());
-    res.set_header("Content-Length", length);
+    res.content_length_ = res.body.size();
+    res.set_header("Content-Length", std::to_string(res.content_length_));
   }
 }
 

+ 18 - 0
test/test.cc

@@ -7499,6 +7499,24 @@ TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
       post_compression_body); // Post-compression logger captures final content
 }
 
+TEST_F(ServerTest, LoggerSeesContentLength) {
+  size_t logged_content_length = 0;
+  std::string logged_content_length_header;
+
+  svr_.set_logger([&](const Request & /*req*/, const Response &res) {
+    logged_content_length = res.content_length_;
+    logged_content_length_header = res.get_header_value("Content-Length");
+  });
+
+  auto res = cli_.Get("/nocompress");
+
+  ASSERT_TRUE(res);
+  EXPECT_EQ(StatusCode::OK_200, res->status);
+  EXPECT_EQ(res->body.size(), logged_content_length);
+  EXPECT_EQ(std::to_string(logged_content_length),
+            logged_content_length_header);
+}
+
 TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
   const std::string test_content =
       "123456789012345678901234567890123456789012345678901234567890123456789012"