-
Notifications
You must be signed in to change notification settings - Fork 191
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #111 from andrewray/server
Toplevel: add a simple cohttp based server
- Loading branch information
Showing
3 changed files
with
72 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
open Lwt | ||
open Cohttp | ||
open Cohttp_lwt_unix | ||
open Re | ||
|
||
let address = ref "127.0.0.1" | ||
let port = ref 8888 | ||
let filesys = ref (Filename.concat (Sys.getenv "HOME") ".opam") | ||
|
||
let server () = | ||
|
||
let re_filesys = compile (seq [ str "/filesys/"; group (rep any); eos ]) in | ||
|
||
let header typ = | ||
let h = Header.init () in | ||
let h = Header.add h "Content-Type" typ in | ||
let h = Header.add h "Server" "iocaml" in | ||
h | ||
in | ||
let header_html = header "text/html; charset=UTF-8" in | ||
let header_plain_user_charset = header "text/plain; charset=x-user-defined" in | ||
|
||
let callback conn_id req body = | ||
let uri = Request.uri req in | ||
let path = Uri.path uri in | ||
|
||
try | ||
(* send binary file *) | ||
let fname = get (exec re_filesys path) 1 in | ||
Lwt_io.eprintf "filesys: %s\n" fname >>= fun () -> | ||
Server.respond_file ~headers:header_plain_user_charset ~fname:fname () | ||
with _ -> | ||
(* send static file *) | ||
let fname = Server.resolve_file ~docroot:"." ~uri:uri in | ||
Lwt_io.eprintf "static: %s\n" fname >>= fun () -> | ||
Server.respond_file ~headers:header_html ~fname:fname () | ||
|
||
in | ||
let conn_closed conn_id () = () in | ||
let config = { Server.callback; conn_closed } in | ||
Server.create ~address:!address ~port:!port config | ||
|
||
let () = Lwt_unix.run (server()) | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters