feat: Server.run takes ?after_init parameter

also use it in http_of_dir to print the actual port.
This commit is contained in:
Simon Cruanes 2023-05-24 15:38:38 -04:00
parent 04fb648576
commit 88bfb9c109
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4
3 changed files with 17 additions and 10 deletions

View file

@ -897,7 +897,7 @@ let handle_client_ (self : t) (client_sock : Unix.file_descr) : unit =
let is_ipv6 self = String.contains self.addr ':'
let run (self : t) : (unit, _) result =
let run ?(after_init = ignore) (self : t) : (unit, _) result =
try
if self.masksigpipe then
ignore (Unix.sigprocmask Unix.SIG_BLOCK [ Sys.sigpipe ] : _ list);
@ -925,6 +925,7 @@ let run (self : t) : (unit, _) result =
Unix.listen sock (2 * self.sem_max_connections.Sem_.n)
);
self.sock <- Some sock;
after_init ();
while self.running do
(* limit concurrency *)
Sem_.acquire 1 self.sem_max_connections;

View file

@ -542,13 +542,17 @@ val stop : t -> unit
(** Ask the server to stop. This might not have an immediate effect
as {!run} might currently be waiting on IO. *)
val run : t -> (unit, exn) result
val run : ?after_init:(unit -> unit) -> t -> (unit, exn) result
(** Run the main loop of the server, listening on a socket
described at the server's creation time, using [new_thread] to
start a thread for each new client.
This returns [Ok ()] if the server exits gracefully, or [Error e] if
it exits with an error. *)
it exits with an error.
@param after_init is called after the server starts listening. @since NEXT_RELEASE .
*)
(**/**)

View file

@ -5,15 +5,17 @@ module Pf = Printf
let serve ~config (dir : string) addr port j : _ result =
let server = S.create ~max_connections:j ~addr ~port () in
Printf.printf "serve directory %s on http://%(%s%):%d\n%!" dir
(if S.is_ipv6 server then
"[%s]"
else
"%s")
addr port;
let after_init () =
Printf.printf "serve directory %s on http://%(%s%):%d\n%!" dir
(if S.is_ipv6 server then
"[%s]"
else
"%s")
addr (S.port server)
in
D.add_dir_path ~config ~dir ~prefix:"" server;
S.run server
S.run ~after_init server
let parse_size s : int =
try Scanf.sscanf s "%dM" (fun n -> n * 1_024 * 1_024)