Created
June 19, 2017 20:57
-
-
Save dudelson/4b418e09c66c9d872d1fa81d7a0b20e9 to your computer and use it in GitHub Desktop.
A minimal example of how to use ocaml-webmachine to build a REST API. This API returns HTTP error 406 ("Not Acceptable") for every valid request
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
(** Returns http error 406 for every valid request. | |
build with: `ocamlbuild -use-ocamlfind -pkgs cohttp.lwt,lwt,webmachine main.byte` *) | |
open Cohttp | |
open Cohttp_lwt_unix | |
open Lwt.Infix | |
module Wm = struct | |
include Webmachine.Make(Cohttp_lwt_unix_io) | |
module Rd = Webmachine.Rd | |
end | |
class handler = object(self) | |
inherit [Cohttp_lwt_body.t] Wm.resource | |
method content_types_accepted rd = Wm.continue [] rd | |
method content_types_provided rd = Wm.continue [] rd | |
end | |
let main () = | |
let routes = [ | |
("/foo", fun () -> new handler); | |
("/bar/:id", fun() -> new handler); | |
] in | |
let callback _conn request body = | |
Wm.dispatch' routes body request >|= (function | |
| Some r -> r | |
| None -> (`Not_found, Header.init (), `String "Nope sorry", [])) | |
>>= (fun (status, headers, body, path) -> | |
Server.respond ~status ~headers ~body ()) in | |
Server.create ~mode:(`TCP (`Port 8081)) (Server.make ~callback ()) | |
let () = Lwt_main.run(main ()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment