这是使用库Cohttp的一个简单示例:
open Lwt
open Cohttp
open Cohttp_lwt_unix
let body =
Client.get (Uri.of_string "http://www.reddit.com/") >>= fun (resp, body) ->
let code = resp |> Response.status |> Code.code_of_status in
Printf.printf "Response code: %d\n" code;
Printf.printf "Headers: %s\n" (resp |> Response.headers |> Header.to_string);
body |> Cohttp_lwt.Body.to_string >|= fun body ->
Printf.printf "Body of length: %d\n" (String.length body);
body
let () =
let body = Lwt_main.run body in
print_endline ("Received body\n" ^ body)
Run Code Online (Sandbox Code Playgroud)
我正在尝试编译它
ocaml my_test1.ml
Run Code Online (Sandbox Code Playgroud)
错误:
错误:未绑定模块Lwt
如何在我的应用程序中实际包含/要求模块Lwt?
更新
也:
$ ocamlbuild
bash: ocamlbuild: command not found
Run Code Online (Sandbox Code Playgroud)
但:
$ opam install ocamlbuild
[NOTE] Package ocamlbuild is already installed (current version is
0.12.0).
Run Code Online (Sandbox Code Playgroud)
和
$ opam install ocamlfind
[NOTE] Package ocamlfind is already installed (current version is
1.7.3-1).
Run Code Online (Sandbox Code Playgroud)
和
$ ocamlfind
bash: ocamlfind: command not found
Run Code Online (Sandbox Code Playgroud)
ocamlfind和ocamlbuild在哪里?
UPDATE2
$ ocamlfind ocamlc -package lwt -c my_test1.ml
File "my_test1.ml", line 2, characters 5-11:
Error: Unbound module Cohttp
Run Code Online (Sandbox Code Playgroud)
根据您的需要,您有多种选择.
1)如果你想为你的二进制文件创建一个完整的项目,我建议你看一下jbuilder.这是一个非常好的指南,逐步解释环境/项目配置:OCaml为不耐烦.
2)另一种选择是直接编译二进制文件,如你所想:
ocamlbuild -pkg lwt -pkg cohttp-lwt-unix my_test1.native
Run Code Online (Sandbox Code Playgroud)
请注意,您需要有一个名为my_test1.ml生成请求的文件my_test1.native.
3)最后,对于快速脚本,我发现能够让OCaml解释器直接在源文件中加载依赖项是很方便的.只需将以下内容添加到文件的开头:
#use "topfind";;
#require "lwt";;
#require "cohttp-lwt-unix";;
Run Code Online (Sandbox Code Playgroud)
然后运行ocaml my_test1.ml.
希望这可以帮助!:)
另外,看看command not found你得到的错误我可以建议你确保你的环境配置正确.真实世界OCaml书有一个维基页面:https://github.com/realworldocaml/book/wiki/Installation-Instructions