Skip to content

Instantly share code, notes, and snippets.

@anmonteiro
Last active August 5, 2018 21:13
Show Gist options
  • Save anmonteiro/4de03a916da66e73f879a5672b2068fd to your computer and use it in GitHub Desktop.
Save anmonteiro/4de03a916da66e73f879a5672b2068fd to your computer and use it in GitHub Desktop.
Server-sent events in http/af
let set_interval = (s, f, destroy) => {
let rec set_interval_loop = (s, f, n) => {
let timeout =
Lwt_timeout.create(s, () =>
if (n > 0) {
f();
set_interval_loop(s, f, n - 1);
} else {
destroy();
}
);
Lwt_timeout.start(timeout);
};
set_interval_loop(s, f, 5);
};
let response =
Response.create(
`OK,
~headers=
Headers.of_list([
("Connection", "close"),
("Content-Type", "text/event-stream"),
]),
);
let request_body = Reqd.request_body(reqd);
let response_body = Reqd.respond_with_streaming(reqd, response);
let rec on_read = (_request_data, ~off as _, ~len as _) =>
Body.flush(response_body, () =>
Body.schedule_read(request_body, ~on_eof, ~on_read)
)
and on_eof = () =>
set_interval(
2,
() => {
let _ = Body.write_string(response_body, "data: some data\n\n");
Body.flush(response_body, () => ());
},
() => {
let _ = Body.write_string(response_body, "event: end\ndata: 1\n\n");
Body.flush(response_body, () => Body.close_writer(response_body));
},
);
Body.flush(response_body, () => ());
Body.schedule_read(~on_read, ~on_eof, request_body);
Lwt.return_unit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment