2016-11-07 58 views
1

我正在按照教程解釋如何在OCaml中使用lwtCohttp來製作簡單的Web服務器。錯誤:未綁定的記錄字段Server.callback - Ocaml

我有一個_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 }它也會t rigger:

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

我不知道如何解決這個問題,所以在此先感謝您進行調查。

回答

2

可能是,您正在使用一個非常過時的教程,它是爲舊的cohttp界面編寫的。您可以嘗試查看the upstream repository中的最新教程。

在你的情況,至少有以下修改的話,編譯程序:

  1. 您應該使用功能Server.make創建一個服務器的實例;
  2. callbackconn_closed值應爲函數參數傳遞,而不是作爲一個記錄,例如,

    Server.make ~callback ~conn_closed() 
    
  3. 您應該使用功能Server.create並傳遞價值,這是從功能Server.make返回創建服務器實例。

所以,很可能,下面應該工作:

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()) 
+0

它呢!感謝您的非常詳細的答案。 –