diff --git a/src/Tiny_httpd_server.ml b/src/Tiny_httpd_server.ml index 835a3f7f..93ca2e88 100644 --- a/src/Tiny_httpd_server.ml +++ b/src/Tiny_httpd_server.ml @@ -480,7 +480,7 @@ module Response = struct k "output response: %s" (Format.asprintf "%a" pp { self with body = `String "<...>" })); - (* write headers *) + (* write headers, using [buf] to batch writes *) List.iter (fun (k, v) -> Printf.bprintf tmp_buffer "%s: %s\r\n" k v; @@ -490,12 +490,16 @@ module Response = struct IO.Out_channel.output_buf oc buf; IO.Out_channel.output_string oc "\r\n"; + (* flush after writing headers *) + IO.Out_channel.flush oc; + Buf.clear buf; (match body with | `String "" | `Void -> () | `String s -> IO.Out_channel.output_string oc s | `Writer w -> - let oc' = IO.Out_channel.chunk_encoding ~close_rec:false oc in + (* use buffer to chunk encode [w] *) + let oc' = IO.Out_channel.chunk_encoding ~buf ~close_rec:false oc in (try IO.Writer.write oc' w; IO.Out_channel.close oc' @@ -504,7 +508,7 @@ module Response = struct raise e) | `Stream str -> (try - Byte_stream.output_chunked' oc str; + Byte_stream.output_chunked' ~buf oc str; Byte_stream.close str with e -> Byte_stream.close str; diff --git a/src/Tiny_httpd_stream.ml b/src/Tiny_httpd_stream.ml index e5cfb5e4..cdaad2e2 100644 --- a/src/Tiny_httpd_stream.ml +++ b/src/Tiny_httpd_stream.ml @@ -299,11 +299,11 @@ let read_chunked ?(buf = Buf.create ()) ~fail (bs : t) : t = refill := false) () -let output_chunked' (oc : IO.Out_channel.t) (self : t) : unit = - let oc' = IO.Out_channel.chunk_encoding oc ~close_rec:false in +let output_chunked' ?buf (oc : IO.Out_channel.t) (self : t) : unit = + let oc' = IO.Out_channel.chunk_encoding ?buf oc ~close_rec:false in to_chan' oc' self; IO.Out_channel.close oc' (* print a stream as a series of chunks *) -let output_chunked (oc : out_channel) (self : t) : unit = - output_chunked' (IO.Out_channel.of_out_channel oc) self +let output_chunked ?buf (oc : out_channel) (self : t) : unit = + output_chunked' ?buf (IO.Out_channel.of_out_channel oc) self diff --git a/src/Tiny_httpd_stream.mli b/src/Tiny_httpd_stream.mli index 519128fa..7f8b38b8 100644 --- a/src/Tiny_httpd_stream.mli +++ b/src/Tiny_httpd_stream.mli @@ -149,9 +149,11 @@ val read_exactly : @param too_short is called if [bs] closes with still [n] bytes remaining *) -val output_chunked : out_channel -> t -> unit -(** Write the stream into the channel, using the chunked encoding. *) +val output_chunked : ?buf:Tiny_httpd_buf.t -> out_channel -> t -> unit +(** Write the stream into the channel, using the chunked encoding. + @param buf optional buffer for chunking (since NEXT_RELEASE) *) -val output_chunked' : Tiny_httpd_io.Out_channel.t -> t -> unit +val output_chunked' : + ?buf:Tiny_httpd_buf.t -> Tiny_httpd_io.Out_channel.t -> t -> unit (** Write the stream into the channel, using the chunked encoding. @since NEXT_RELEASE *)