dream/example/w-template-stream
Anton Bachin c5514d72e3 Use esy
2021-04-21 10:49:15 +03:00
..
2021-03-28 23:15:47 +03:00
2021-03-28 23:15:47 +03:00
2021-04-21 10:49:15 +03:00
2021-04-21 10:49:15 +03:00

w-template-stream


This example streams a template as a response body. It sends one paragraph per second to the client:

let render response =
  let%lwt () =
    %% response
    <html>
      <body>

%       let rec paragraphs index =
          <p><%i index %></p>
%         let%lwt () = Dream.flush response in
%         let%lwt () = Lwt_unix.sleep 1. in
%         paragraphs (index + 1)
%       in
%       let%lwt () = paragraphs 0 in

      </body>
    </html>
  in
  Dream.close_stream response

let () =
  Dream.run
  @@ Dream.logger
  @@ fun _ -> Dream.stream render
$ npm install esy && npx esy
$ npx esy start

Most uses of streaming don't need Dream.flush, but we are using it here to prevent buffering of each paragraph.


See also:

  • 7-template section Security on security considerations with templates, and in general.
  • r-template-stream is a Reason syntax version of this example.

Up to the example index