rgrinberg / opium

Sinatra like web toolkit for OCaml
MIT License
755 stars 67 forks source link

Can we simulate slow internet connection by delay opium's response? #55

Closed liweijian closed 4 years ago

liweijian commented 8 years ago

Normally, we wrote code to response as soon as possible, for example:

let getid req =
  let uri = Request.uri req in
  let ua = Option.value (Uri.get_query_param uri "ua") ~default:"na"
  in App.string_of_body_exn req >>| fun rbody ->
  print_endline ("body: "^rbody^", param:"^ua);
  respond (`String (rbody^ua))

In some situations we need to simulate slow internet connection by delay the response, I was wondering can we do that in opium?

rgrinberg commented 8 years ago

You should return a response constructed from a Lwt_stream.t:

https://github.com/rgrinberg/ocaml-cohttp/blob/5c68585259ef4d5a2bf9c2250cbadfae94704241/lwt-core/cohttp_lwt_body.mli#L19

Then it's just a question of constructing an Lwt_stream that returns chunks with a delay.

Let me know if that isn't clear enough and I will whip up a demo

liweijian commented 8 years ago

@rgrinberg ,thank you for your reply.

I have tried to read the documents of both cohttp_lwt_body and Lwt_stream API, this is the first time I use Lwt library.

I tried to write some examples of Lwt_stream, but there're errrors, for example:

let delay_resp req =
  let ret_str = "hello" in
  respond (`Stream (Lwt_stream.of_string ret_str))
martindemello commented 7 years ago

+1 for adding an example that uses streaming

anuragsoni commented 4 years ago

Version 0.18.0 added support for streaming responses.

Example with cohttp + Lwt_stream https://github.com/rgrinberg/opium/blob/6ce8a21223b0d74a77d5ea0160d86f49db94ace1/examples/hello_world.ml#L13-L29

Note that the current master branch has switched to httpaf. Example with httpaf + streams

https://github.com/rgrinberg/opium/blob/663e4aa100ae69166ff13a22018261008a01cac2/examples/hello_world.ml#L20-L26