2021-03-26 01:20:37 +03:00
..
2021-03-24 17:33:35 +03:00
2021-03-24 17:33:35 +03:00
2021-03-25 11:58:09 +03:00
2021-03-26 01:20:37 +03:00

5-echo


This example just echoes the bodies of POST /echo requests:

let () =
  Dream.run
  @@ Dream.logger
  @@ Dream.router [
    Dream.post "/echo" (fun request ->
      Lwt.map Dream.response (Dream.body request));
  ]
  @@ Dream.not_found
$ dune exec --root . ./echo.exe

You can test it with curl:

$ curl http://localhost:8080/echo --data foo
foo

Or try HTTPie:

$ echo -n foo | http POST :8080/echo
HTTP/1.1 200 OK
Content-Length: 3

foo

The code uses Lwt.map. That's because Dream.body returns the body string inside a promise, and we want to transform that string promise into a response promise with Dream.response. This is just a touch of Lwt, because we need it here! Example a-promise introduces Lwt promises fully.


We usually want to do something more interesting with the request body than just echo it, and there are several examples for that!

We delay these examples a bit, so we can squeeze in a couple security topics first. These examples do take client input, after all! So, it's better to present them the right way.


Next steps:

  • 6-template renders responses from templates and guards against injection attacks (XSS).
  • 7-debug renders error information in responses.

Up to the tutorial index