-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdispatch.ml
55 lines (48 loc) · 1.45 KB
/
dispatch.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
open Lwt
open Printf
open V1_LWT
module Main (C:CONSOLE) (FS:KV_RO) (S:Cohttp_lwt.Server) = struct
let start c fs http =
let read_fs name =
FS.size fs name
>>= function
| `Error (FS.Unknown_key _) -> fail (Failure ("read " ^ name))
| `Ok size ->
FS.read fs name 0 (Int64.to_int size)
>>= function
| `Error (FS.Unknown_key _) -> fail (Failure ("read " ^ name))
| `Ok bufs -> return (Cstruct.copyv bufs)
in
(* Split a URI into a list of path segments *)
let split_path uri =
let path = Uri.path uri in
let rec aux = function
| [] | [""] -> []
| hd::tl -> hd :: aux tl
in
List.filter (fun e -> e <> "")
(aux (Re_str.(split_delim (regexp_string "/") path)))
in
(* dispatch non-file URLs *)
let rec dispatcher = function
| [] | [""] -> dispatcher ["index.html"]
| segments ->
let path = String.concat "/" segments in
try_lwt
read_fs path
>>= fun body ->
S.respond_string ~status:`OK ~body ()
with exn ->
S.respond_not_found ()
in
(* HTTP callback *)
let callback conn_id request body =
let uri = S.Request.uri request in
dispatcher (split_path uri)
in
let conn_closed (_,conn_id) =
let cid = Cohttp.Connection.to_string conn_id in
C.log c (Printf.sprintf "conn %s closed" cid)
in
http (S.make ~conn_closed ~callback ())
end