changeset 14076:a558af9e8c35

net.http.server: Allow sending a file slice To enable implementing Range requests
author Kim Alvefur <zash@zash.se>
date Fri, 21 Nov 2025 21:41:35 +0100
parents 7a31775f1d7f
children c83aee2a0b11
files net/http/server.lua
diffstat 1 files changed, 11 insertions(+), 9 deletions(-) [+]
line wrap: on
line diff
--- a/net/http/server.lua	Fri Nov 21 21:40:29 2025 +0100
+++ b/net/http/server.lua	Fri Nov 21 21:41:35 2025 +0100
@@ -365,7 +365,7 @@
 	response.conn:write(t_concat(output));
 	response:done();
 end
-function _M.send_file(response, f)
+function _M.send_file(response, f, length)
 	if response.is_head_request then
 		if f.close then f:close(); end
 		return _M.send_head_response(response);
@@ -379,14 +379,11 @@
 			incomplete[response.conn] = nil;
 			return;
 		end
-		local chunk = f:read(blocksize);
-		if chunk then
-			if chunked then
-				chunk = ("%x\r\n%s\r\n"):format(#chunk, chunk);
-			end
-			-- io.write("."); io.flush();
-			response.conn:write(chunk);
-		else
+		local chunksize = blocksize;
+		if length and length < chunksize then chunksize = length; end
+
+		local chunk = chunksize > 0 and f:read(chunksize);
+		if not chunk then
 			incomplete[response.conn] = nil;
 			if f.close then f:close(); end
 			if chunked then
@@ -394,6 +391,11 @@
 			end
 			-- io.write("\n");
 			return response:done();
+		else
+			if length then length = length - #chunk; end
+			if chunked then chunk = ("%x\r\n%s\r\n"):format(#chunk, chunk); end
+			-- io.write("."); io.flush();
+			response.conn:write(chunk);
 		end
 	end
 	_M.write_headers(response);