Skip to content

Commit 29d1076

Browse files
authored
Cookbook: "Start a Web Server" with dream and cohttp (#3166)
1 parent 198a04e commit 29d1076

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
---
2+
packages:
3+
- name: "cohttp-lwt-unix"
4+
tested_version: "5.3.0"
5+
used_libraries:
6+
- cohttp-lwt-unix
7+
- name: "lwt"
8+
tested_version: "5.7.0"
9+
used_libraries:
10+
- lwt
11+
- lwt.infix
12+
discussion: |
13+
This example shows how to use `cohttp-lwt-unix` to start an HTTP server in OCaml using `Lwt`
14+
---
15+
(* The server:
16+
- Handles any incoming request on port 8080
17+
- Responds with a static `Hello world` message
18+
- Uses Server.respond_string to return a simple text response
19+
`Lwt (Lwt.Infix)` is used for chaining asynchronous computations *)
20+
open Lwt.Infix
21+
open Cohttp_lwt_unix
22+
23+
let () =
24+
let callback _conn _req body =
25+
Cohttp_lwt.Body.drain_body body >>= fun () ->
26+
Server.respond_string ~status:`OK ~body:"Hello world" ()
27+
in
28+
let server = Server.make ~callback () in
29+
let port = 8080 in
30+
let mode = `TCP (`Port port) in
31+
Format.printf "listening on http://localhost:%d\n%!" port;
32+
Server.create ~mode server |> Lwt_main.run
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
packages:
3+
- name: "dream"
4+
tested_version: "1.0.0~alpha8"
5+
used_libraries:
6+
- dream
7+
discussion: |
8+
This example uses Dream, a simple and type-safe web framework for OCaml.
9+
---
10+
(* The server:
11+
- Handles any incoming request on port 8080
12+
- Logs requests
13+
- Responds with a static `Hello world` message
14+
- Returns 404 error for other routes *)
15+
16+
let () =
17+
Dream.run
18+
@@ Dream.logger
19+
@@ Dream.router [
20+
Dream.get "/" (fun _ -> Dream.html "Hello World!");
21+
Dream.any "/" (fun _ -> Dream.empty `Not_Found);
22+
]

0 commit comments

Comments
 (0)