drame/example/main.ml

78 lines
2 KiB
OCaml
Raw Normal View History

2024-01-04 16:59:51 +01:00
module App_id = struct
let qualifier = "org"
let organization = "drame"
let application = "drame"
end
2026-03-08 17:45:32 +01:00
module Server = Drame.Server.Make (App_id)
2024-01-04 16:59:51 +01:00
2026-03-08 17:45:32 +01:00
let template_html (_request : Drame.Request.t) ~title ~body =
let open Htmlit in
El.html
~at:[ At.lang "en" ]
[ El.head
[ El.title [ El.txt title ]
; El.link
~at:[ At.rel "stylesheet"; At.href "/assets/css/style.css" ]
()
]
; El.body [ El.main [ El.h1 [ El.txt title ]; body ] ]
]
2024-01-04 16:59:51 +01:00
2026-03-08 17:45:32 +01:00
let hello ~name request =
let title = Fmt.str "Hello %s!" name in
let body = Htmlit.El.txt "How are you doing?" in
let doc = template_html request ~title ~body in
let content = Drame.Content.Html doc in
Ok content
2024-01-04 16:59:51 +01:00
let hello_q request =
2026-03-08 17:45:32 +01:00
let name =
Drame.Request.query request "name" |> Option.value ~default:"World"
in
let title = Fmt.str "Hello %s!" name in
let body = Htmlit.El.txt title in
let doc = template_html request ~title ~body in
let content = Drame.Content.Html doc in
2024-01-04 16:59:51 +01:00
Ok content
2026-03-08 17:45:32 +01:00
let config request =
let title = "Configuration" in
let body = Fmt.kstr Htmlit.El.txt "%a" Scfg.Pp.config Server.config in
let doc = template_html request ~title ~body in
let content = Drame.Content.Html doc in
Ok content
2024-01-04 16:59:51 +01:00
2026-03-08 17:45:32 +01:00
let not_found request =
let title = "404 Not Found" in
let body = Htmlit.El.txt "Ooops :S" in
let content = template_html request ~title ~body in
Error (Drame.Status.Not_found, content)
2024-01-04 16:59:51 +01:00
2026-03-08 17:45:32 +01:00
let style _request =
2024-01-04 16:59:51 +01:00
let sheet =
2026-03-08 17:45:32 +01:00
{css|
body {
color: #ebb2bf;
background-color: #0f1312;
}
|css}
2024-01-04 16:59:51 +01:00
in
2026-03-08 17:45:32 +01:00
let content = Drame.Content.Unsafe { content = sheet; mimetype = Text_css } in
Ok content
2024-01-04 16:59:51 +01:00
let handler route =
2026-03-08 17:45:32 +01:00
Fmt.pr "[request] %a@\n" Drame.Route.pp route;
2024-01-04 16:59:51 +01:00
Fmt.flush Fmt.stdout ();
match route with
| [||] -> hello ~name:"World"
| [| "assets"; "css"; "style.css" |] -> style
| [| "config" |] -> config
| [| "hello"; name |] -> hello ~name
| [| "helloq" |] -> hello_q
| _ -> not_found
let () = Server.run ~handler