mirror of
https://github.com/aantron/dream.git
synced 2025-12-31 00:03:52 -05: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!
d-formparses request bodies as forms.e-jsonparses them as JSON.g-uploadreceives file upload forms.i-graphqlreceives GraphQL queries!j-streamingstreams huge bodies.
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-templaterenders responses from templates and guards against injection attacks (XSS).7-debugrenders error information in responses.