close fd correctly

This commit is contained in:
craff 2021-12-19 00:49:09 -10:00
parent 3067120539
commit 912c7b1fd7
3 changed files with 14 additions and 12 deletions

View file

@ -204,9 +204,10 @@ let add_dir_path ~config ~dir ~prefix server =
S.Response.make_raw ~code:405 "listing dir not allowed"
) else (
try
let bs = Bigstring_unix.with_map_file ~flags:[Open_rdonly] full_path
(fun s -> s)
in
let fd = Unix.(openfile full_path [O_RDONLY] 0) in
let len = stat.Unix.st_size in
let bs = Bigstring_unix.map_file_descr fd len in
Gc.finalise (fun _ -> Unix.close fd) bs;
let mime_type =
if Filename.extension full_path = ".css" then (
["Content-Type", "text/css"]
@ -224,10 +225,8 @@ let add_dir_path ~config ~dir ~prefix server =
~headers:(mime_type@["Etag", mtime_str])
~code:200 bs
with e ->
S.Response.fail ~code:500 "error while reading file: %s" (Printexc.to_string e))
)
) else (
S.Response.fail ~code:500 "error while reading file: %s" (Printexc.to_string e)))) else (
S.add_route_handler server ~meth:`GET
S.Route.(exact_path prefix (string @/ return))
(fun _ _ -> S.Response.make_raw ~code:405 "download not allowed");
);
);

View file

@ -1,2 +1,5 @@
serve directory . on http://127.0.0.1:8084
0 0 52428800 data2
0 0 52428800 data21
0 0 52428800 data22
0 0 52428800 data23
0 0 157286400 total

View file

@ -8,16 +8,16 @@ PID=$!
sleep 0.1
echo download1 1>&2
curl -N "http://localhost:${PORT}/foo_50" -o data2 \
curl -N "http://localhost:${PORT}/foo_50" -o data21 \
-H 'Tranfer-encoding: chunked'
echo download2 1>&2
curl -N "http://localhost:${PORT}/foo_50" -o data2 \
curl -N "http://localhost:${PORT}/foo_50" -o data22 \
-H 'Tranfer-encoding: chunked'
echo download3 1>&2
curl -N "http://localhost:${PORT}/foo_50" -o data2 \
curl -N "http://localhost:${PORT}/foo_50" -o data23 \
-H 'Tranfer-encoding: chunked'
kill $PID
wc data2
wc data21 data22 data23