From 5827328993ca0633ecddc83f3a73cc506b5e0f92 Mon Sep 17 00:00:00 2001 From: Simon Cruanes Date: Sat, 11 Dec 2021 16:48:16 -0500 Subject: [PATCH] feat: add `?middlewares` param to `create` --- src/Tiny_httpd.ml | 11 ++++++++--- src/Tiny_httpd.mli | 3 +++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Tiny_httpd.ml b/src/Tiny_httpd.ml index bd1a9828..f86d4d65 100644 --- a/src/Tiny_httpd.ml +++ b/src/Tiny_httpd.ml @@ -989,14 +989,19 @@ let create ?(timeout=0.0) ?(buf_size=16 * 1_024) ?(new_thread=(fun f -> ignore (Thread.create f () : Thread.t))) - ?(addr="127.0.0.1") ?(port=8080) ?sock () : t = + ?(addr="127.0.0.1") ?(port=8080) ?sock + ?(middlewares=[]) + () : t = let handler _req = Response.fail ~code:404 "no top handler" in let max_connections = max 4 max_connections in - { new_thread; addr; port; sock; masksigpipe; handler; buf_size; + let self = { + new_thread; addr; port; sock; masksigpipe; handler; buf_size; running= true; sem_max_connections=Sem_.create max_connections; path_handlers=[]; timeout; middlewares=[]; middlewares_sorted=lazy []; - } + } in + List.iter (fun (stage,m) -> add_middleware self ~stage m) middlewares; + self let stop s = s.running <- false diff --git a/src/Tiny_httpd.mli b/src/Tiny_httpd.mli index 18cf6ddd..2a56f434 100644 --- a/src/Tiny_httpd.mli +++ b/src/Tiny_httpd.mli @@ -496,6 +496,7 @@ val create : ?addr:string -> ?port:int -> ?sock:Unix.file_descr -> + ?middlewares:([`Encoding | `Stage of int] * Middleware.t) list -> unit -> t (** Create a new webserver. @@ -513,6 +514,8 @@ val create : new client connection. By default it is {!Thread.create} but one could use a thread pool instead. + @param middlewares see {!add_middleware} for more details. + @param max_connections maximum number of simultaneous connections. @param timeout connection is closed if the socket does not do read or write for the amount of second. Default: 0.0 which means no timeout.