错误:未绑定的记录字段Server.callback - Ocaml

时间:2016-11-07 17:58:57

标签: webserver ocaml ocaml-lwt

我正在按照教程解释如何使用lwtCohttp在OCaml中创建简单的Web服务器。

我有一个_tags文件,其中包含以下内容:

true: package(lwt), package(cohttp), package(cohttp.lwt)

webserver.ml

open Lwt
open Cohttp
open Cohttp_lwt_unix

let make_server () =
  let callback conn_id req body =
    let uri = Request.uri req in
    match Uri.path uri with
    | "/" -> Server.respond_string ~status:`OK ~body:"hello!\n" ()
    | _ -> Server.respond_string ~status:`Not_found ~body:"Route not found" ()
  in
  let conn_closed conn_id () = () in
  Server.create { Server.callback; Server.conn_closed }

let _ =
  Lwt_unix.run (make_server ())

然后,ocamlbuild -use-ocamlfind webserver.native会触发以下错误:

Error: Unbound record field callback
Command exited with code 2.

如果我改为:Server.create { callback; conn_closed },它也会触发:

Error: Unbound record field callback
Command exited with code 2.

我不知道如何解决这个问题,所以提前感谢您对此进行调查。

1 个答案:

答案 0 :(得分:3)

可能您正在使用一个非常过时的教程,该教程是为旧的cohttp接口编写的。您可以尝试查看the upstream repository中的最新教程。

在您的情况下,至少应进行以下更改,以编译程序:

  1. 您应该使用函数Server.make来创建服务器实例;
  2. callbackconn_closed值应作为函数参数传递,而不是作为记录传递,例如,

    Server.make ~callback ~conn_closed ()
    
  3. 您应该使用函数Server.create并传递一个从函数Server.make返回的值来创建服务器实例。

  4. 因此,可能以下情况应该有效:

    open Lwt
    open Cohttp
    open Cohttp_lwt_unix
    
    let make_server () =
      let callback conn_id req body =
        let uri = Request.uri req in
        match Uri.path uri with
        | "/" -> Server.respond_string ~status:`OK ~body:"hello!\n" ()
        | _ -> Server.respond_string ~status:`Not_found ~body:"Route not found" ()
      in
      Server.create (Server.make ~callback ())
    
    let _ =
      Lwt_unix.run (make_server ())
    
相关问题