该Ocsigen/Eliom教程开始与提供了一个应用实例"你好,世界!" 作为HTML:
open Eliom_content.Html5.D
let main_service =
Eliom_registration.Html5.register_service
~path:["graff"]
~get_params:Eliom_parameter.unit
(fun () () ->
Lwt.return
(html
(head (title (pcdata "Page title")) [])
(body [h1 [pcdata "Graffiti"]])))
Run Code Online (Sandbox Code Playgroud)
如何将其作为JSON服务呢?具体来说,如何注册JSON服务,以及应该使用哪些库/组合器来生成/序列化JSON(js_of_ocaml?)?
小智 6
我不确定你想要做什么,但是,关于JSON,你可以使用"衍生"(参见Deriving_Json)来创建一个JSON类型,使用类似这样的OCaml类型:
type deriving_t = (string * string) deriving (Json)
Run Code Online (Sandbox Code Playgroud)
这将创建与OCaml类型对应的JSON类型.
这里使用这种类型与服务器通信的方式(如果你不知道服务器功能,这里有关于它的文档和服务器端的客户端值):
(* first you have to create a server function (this allowed the client to call a function from the server *)
let json_call =
server_function
Json.t<deriving_t>
(fun (a,b) ->
Lwt.return (print_endline ("log on the server: "^a^b)))
(* let say that distillery has already generate all the needed stuff (main_service, Foobar_app, etc..) *)
let () =
Foobar_app.register
~service:main_service
(fun () () ->
{unit{
(* here I call my server function by using ocaml types directly, it will be automatically serialize *)
ignore (%json_call ("hello", "world"))
}};
Lwt.return
(Eliom_tools.F.html
~title:"foobar"
~css:[["css";"foobar.css"]]
Html5.F.(body [
h2 [pcdata "Welcome from Eliom's distillery!"];
])))
Run Code Online (Sandbox Code Playgroud)
如果您想使用某些客户端/服务器通信,您应该查看Eliom_bus,Eliom_comet或Eliom_react.
(对不起,我不能超过2个链接:)但你会在ocsigen.org网站上找到文档).
希望能帮到你.