Web Development
Features: routing, sessions, CSRF, WebSockets, templates (.eml.html), SQL via Caqti, HTTPS.
44.1 Dream — a simple web framework
Features: routing, sessions, CSRF, WebSockets, templates (.eml.html), SQL via Caqti, HTTPS.
let () =
Dream.run ~port:8080
@@ Dream.logger
@@ Dream.router [
Dream.get "/" (fun _ -> Dream.html "Hello from OCaml!");
Dream.get "/hello/:name" (fun req ->
Dream.html ("Hello, " ^ Dream.param req "name"));
Dream.post "/api/echo" (fun req ->
let%lwt body = Dream.body req in
Dream.json body);
]44.2 Other web stacks
Cohttp — low-level HTTP client/server (Lwt/Async/Eio).
Piaf, httpun / h2 — HTTP/1.1 & HTTP/2.
Opium — Sinatra-like framework.
Ocsigen / Eliom — full-stack client+server in one language.
Tyxml — statically checked HTML.
(* HTTP client with cohttp-lwt-unix *)
let fetch url =
let open Lwt.Syntax in
let* resp, body = Cohttp_lwt_unix.Client.get (Uri.of_string url) in
let code = Cohttp.Response.status resp |> Cohttp.Code.code_of_status in
let* body = Cohttp_lwt.Body.to_string body in
Lwt.return (code, body)44.3 Databases
Caqti — database-agnostic (PostgreSQL, SQLite, MariaDB).
ppx_rapper — typed SQL queries.
sqlite3-ocaml, postgresql-ocaml — direct bindings.
Irmin — Git-like distributed database written in OCaml.
let list_users =
let open Caqti_request.Infix in
(Caqti_type.unit ->* Caqti_type.(t2 int string)) "SELECT id, name FROM users"
let get_users (module Db : Caqti_lwt.CONNECTION) = Db.collect_list list_users ()44.4 MirageOS — unikernels
Compile your application + only the OS libraries it needs into a single bootable VM image (Xen, KVM/Solo5, Unix). Used for secure, minimal network services.
opam install mirage
mirage configure -t hvt && make depend && make build